简体   繁体   English

如何在Unity3D中处理队列?

[英]How to process a Queue in Unity3D?

I've implemented a System.Collections.Queue in my game to gather all the incoming TCP messages. 我已经在游戏中实现了System.Collections.Queue ,以收集所有传入的TCP消息。

For now, I simply process the oldest message in the Queue in Update() (if the queue is not empty) 现在,我只是在Update()中处理Queue中最旧的消息(如果队列不为空)

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; 我已经尝试过协程,但是自yield return null;以来,它什么都没有改变yield return null; seems to wait for next frame (so it's like an Update()). 似乎在等待下一帧(因此就像一个Update())。

You can implement CustomYieldInstruction to wait till your message arrives: 您可以实现CustomYieldInstruction以等待消息到达:

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 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM