Olivier Giniaux
Olivier Giniaux

Reputation: 950

How to process a Queue in Unity3D?

I've implemented a System.Collections.Queue in my game to gather all the incoming TCP messages.

For now, I simply process the oldest message in the Queue in Update() (if the queue is not empty)

However, the time between two frames is often way longer that the time taken to process a message.

I would like to know if there is a way to process a message just when the previous one is completed, without freezing the game.

I've tried with coroutines, but it changed nothing since yield return null; seems to wait for next frame (so it's like an Update()).

Upvotes: 1

Views: 4031

Answers (1)

Umair M
Umair M

Reputation: 10720

You can implement CustomYieldInstruction to wait till your message arrives:

class WaitWhileMessageArrives: CustomYieldInstruction 
{
    Func<bool> m_Predicate;

    public override bool keepWaiting { get { return m_Predicate(); } }

    public WaitWhileMessageArrives(Func<bool> predicate) { m_Predicate = predicate; }
}

use it like this:

(NOTE: this code is just an example to give the basic idea, as you haven't provided your code)

IEnumerator ProcessMessages()
{
    while(yourQueue.Count != 0)
    {
        Message msg = yourQueue.Dequeue();
        yield return new WaitWhileMessageArrives(() => msg.processed);
    }
}

Hope it helps

Upvotes: 2

Related Questions