[英]Waiting for event inside Unity Coroutine?
所以我有一个 Unity 协程方法,其中有一些对象。 这些对象表示从某处服务器收集的值,并在准备就绪时发送Updated
事件。
我想知道最好的方法是在 Unity 的协程中等待更新所有值。
public IEnumerator DoStuff()
{
foreach(var val in _updateableValues)
{
if (val.Value != null) continue;
else **wait for val.Updated to be fired then continue**
}
//... here I do stuff with all the values
// I use the WWW class here, so that's why it's a coroutine
}
做这样的事情最好的方法是什么?
谢谢!
没有内置的直接方法来等待事件本身,但您可以使用同步嵌套协程来等待事件设置的标志:
//Flag
bool eventHappened;
//Event subscriber that sets the flag
void OnEvent(){
eventHappened=true;
}
//Coroutine that waits until the flag is set
IEnumerator WaitForEvent() {
yield return new WaitUntil(eventHappened);
eventHappened=false;
}
//Main coroutine, that stops and waits somewhere within it's execution
IEnumerator MainCoroutine(){
//Other stuff...
yield return StartCoroutine(WaitForEvent());
//Oher stuff...
}
考虑到这一点,创建一个等待UnityEvent
的通用协程很容易:
private IEnumerator WaitUntilEvent(UnityEvent unityEvent) {
var trigger = false;
Action action = () => trigger = true;
unityEvent.AddListener(action.Invoke);
yield return new WaitUntil(()=>trigger);
unityEvent.RemoveListener(action.Invoke);
}
我认为更好的方法是每帧检查服务器,而不是不假思索地等待一段时间。
public IEnumerator DoStuff()
{
/* wait until we have the value we want */
while( value != desiredValue)
yield return null
//after this loop, start the real processing
}
这是我的小修复。
为什么有一个包含一行代码的协程? 我直接在需要的地方使用 WaitUntil。 不过我发现,WaitUntil 不需要布尔值,但需要一个布尔谓词函数 - 所以我在下面的示例中提供了这个。
该示例是来自游戏的真实运行代码。 它在第一个场景中运行,在我开始之前开始播放音乐 - 稍微长一点 - 加载其他东西。
//
public class AudioSceneInitializer : MonoBehaviour
{
[SerializeField] private GlobalEventsSO globalEvents;
//globalEvents is a scriptable object that - in my case - holds all events in the game
[SerializeField] private AudioManager audioManager;
//The audio manager which in my case will raise the audio ready event
[SerializeField] public GameObject audioGO;// contains AudioSources used by AudioManager
private bool audioReady = false;
// Start is called before the first frame update
IEnumerator Start()
{
if (audioManager != null)
//better check, if we don't produce the event, we wait forever
{
//subscribe to event
globalEvents.audioManagerReadyEvent += OnAudioReady;
//do something to raise the event - else we wait forever
audioManager.onInitialization(this);//"this" needed to hand over the audioGO to the AudioManager
// waits until the flag is set;
yield return new WaitUntil(IsAudioReady);
}
//now that we have music playing, we load the actual game
SceneManager.LoadSceneAsync(1, LoadSceneMode.Additive);
}
//Event subscriber that sets the flag
void OnAudioReady()
{
//unsubscribing, if - as in my case - it happens only once in the game
globalEvents.audioManagerReadyEvent -= OnAudioReady;
audioReady = true;
}
//predicate function that WaitUntil expects
private bool IsAudioReady()
{
return audioReady;
}
public void OnDisable()
{
audioManager.onCleanup();
}
}
自旋锁是一种解决方案,但不是 CPU 非常温和的解决方案。 在自旋锁中,您只需等待变量具有特定值,否则会休眠几毫秒。
public IEnumerator DoStuff()
{
/* wait until we have the value we want */
while( value != desiredValue)
yield return new WaitForSeconds(0.001f);
//after this loop, start the real processing
}
也许您可能想考虑重构您的代码,以便不需要自旋锁,但可以实现更多基于中断/事件的方法。 这意味着,如果您更新了一个值并且在它发生之后必须发生某些事情,请在更改该值后直接启动它。 在 C# 中,甚至有一个用于该设计模式的接口INotifyPropertyChanged
(请参阅MSDN ),但您也可以轻松地自己设计它,例如,通过在特定值更改时触发事件。 如果你想要一个比自旋锁更好的解决方案,我们需要更多关于你到底想在这里做出什么反应的信息,但这应该会给你一些想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.