我在游戏中实现了System.Collections.Queue
来收集所有传入的TCP消息。
现在,我只是处理Queue
中Update()
中最早的消息(如果队列不为空)
但是,两帧之间的时间通常比处理消息所用的时间长。
我想知道是否有办法在前一个消息完成时处理消息,而不会冻结游戏。
我尝试使用协同程序,但由于yield return null;
似乎等待下一帧(因此它就像Update()),所以它没有改变。
答案 0 :(得分:2)
您可以实施CustomYieldInstruction
,等待邮件到达:
class WaitWhileMessageArrives: CustomYieldInstruction
{
Func<bool> m_Predicate;
public override bool keepWaiting { get { return m_Predicate(); } }
public WaitWhileMessageArrives(Func<bool> predicate) { m_Predicate = predicate; }
}
像这样使用它:
(注意:此代码只是一个提供基本想法的示例,因为您还没有提供代码)
IEnumerator ProcessMessages()
{
while(yourQueue.Count != 0)
{
Message msg = yourQueue.Dequeue();
yield return new WaitWhileMessageArrives(() => msg.processed);
}
}
希望有所帮助