private readonly Queue<System.Action> actions = new Queue<System.Action>();
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
public static DwkUnityMainThreadDispatcher Instance()
{
if (!instance)
{
throw new System.Exception("UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene.");
public static DwkUnityMainThreadDispatcher Instance()
{
if (!instance)
{
throw new System.Exception("UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene.");
private readonly Queue<System.Action> actions = new Queue<System.Action>(); 这行代码创建了一个队列,用于存储要在主线程中执行的使命。每个使命都是一个System.Action,也就是一个无参数且无返回值的委托。
public void Enqueue(System.Action action) 这个方法用于将一个使命添加到队列中。这个使命将在主线程中执行。lock (actions)这行代码确保了在多线程环境下,添加使命到队列的操作是线程安全的。
public void Update() 这个方法在每一帧都会被Unity调用,它在主线程中执行。在这个方法中,它会执行队列中的全部使命。这是通过在队列中有使命时调用actions.Dequeue().Invoke()来实现的。Dequeue()方法移除并返回队列中的第一个使命,Invoke()方法则执行这个使命。