示例
一
using UnityEngine;
using System.Threading;
public class CoroutineExample : MonoBehaviour
{
private EventWaitHandle waitHandle;
void Start()
{
waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
Debug.Log("Coroutine started");
waitHandle.WaitOne();
Debug.Log("Coroutine resumed after waiting for event");
yield return null;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
waitHandle.Set();
}
}
}
上面的例子中,我们创建了一个EventWaitHandle对象来实现协程暂停和恢复执行。 在MyCoroutine()方法中,我们使用WaitOne()方法来暂停协程,直到EventWaitHandle对象收到信号。在Update()方法中,我们检查用户是否按下空格键,如果是,我们向EventWaitHandle对象发送信号以恢复协程的执行。
另一种
using UnityEngine;
using System.Threading;
public class CoroutineExample : MonoBehaviour
{
private Semaphore semaphore;
void Start()
{
semaphore = new Semaphore(0, 1);
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
Debug.Log("Coroutine started");
semaphore.WaitOne();
Debug.Log("Coroutine resumed after waiting for semaphore");
yield return null;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
semaphore.Release();
}
}
}
在这个例子中,我们使用Semaphore对象来实现协程暂停和恢复执行。在MyCoroutine()方法中,我们使用WaitOne()方法来暂停协程,直到Semaphore对象释放了一个信号。在Update()方法中,我们检查用户是否按下空格键,如果是,我们向Semaphore对象释放一个信号以恢复协程的执行。 请注意,在使用WaitHandle或Semaphore时,您需要小心确保您在正确的线程上调用WaitOne()和Release()方法。在Unity中,您可以使用MonoBehaviour.StartCoroutine()方法在Unity的协程调度器线程上运行协程,然后在主线程上发送信号来暂停和恢复协程的执行。