简易实现Unity多线程解决方案
建议和异步任务模型 System.Threading.Tasks 配合使用。
using UnityEngine; using System.Collections.Generic; using System; using System.Threading; public class ThreadHelper : MonoBehaviour { private static ThreadHelper Current; private Listactions = new List (); private static Thread mainThread; public static bool IsMainThread() { return Thread.CurrentThread == mainThread; } // Use this for initialization void Awake() { Current = this; mainThread = Thread.CurrentThread; } // Update is called once per frame void Update() { var currentActions = new List (); lock (actions) { currentActions.AddRange(actions); foreach (var item in currentActions) actions.Remove(item); } foreach (var action in currentActions) { action(); } } public static void QueueOnMainThread(Action action) { if(IsMainThread()) { action(); return; } lock (Current.actions) { Current.actions.Add(action); } } }