[英]How to call methods with different parameters as Action?
我正在Unity中開發游戲,並且Unity不是線程安全的,因此每當我在不同線程上進行一些計算並想返回Unity時,我都需要將調用排隊在某種隊列中,以便Unity可以執行這些任務並在其中執行Unity線程。 這是我用工具完成工作的代碼:
public class Test : MonoBehaviour
{
Thread someThread;
private void Awake() //Executes on application start
{
someThread = new Thread(SomeThreadMethod);
someThread.Start();
}
void SomeThreadMethod()
{
ExecuteInUpdate(MethodCalledNotInUnityThread);
}
// methods that I call from not unity thread but want to execute it IN unity thread
void MethodCalledNotInUnityThread()
{
Debug.Log("Hello from UnityThread");
}
//--------------------------------------------------------------------------------
//Tool for executing things in Unity Thread
List<Action> actionQueues = new List<Action>();
List<Action> actionCopiedQueue = new List<Action>();
private volatile static bool noActionQueue = true;
public void ExecuteInUpdate(Action _action)
{
lock (actionQueues)
{
actionQueues.Add(action);
noActionQueue = false;
}
}
public void Update()//runs all time, sort of while(true) loop in unity thread
{
if (noActionQueue)
{
return;
}
actionCopiedQueue.Clear();
lock (actionQueues)
{
actionCopiedQueue.AddRange(actionQueues);
actionQueues.Clear();
noActionQueue = true;
}
for (int i = 0; i < actionCopiedQueue.Count; i++)
{
actionCopiedQueue[i]();
}
}
}
但是問題在於它僅適用於不帶參數的方法。 如果我做了類似的方法:
void MethodCalledNotInUnityThread1(int _arg)
{
Debug.Log("Hello from UnityThread" + _arg);
}
我無法調用它,因為它具有參數。 我嘗試使用具有通用參數的Action
Action<int> action
但是然后我只能傳遞僅帶有一個參數的方法,它是int的。 我有很多方法可以采用不同數量的diffenet參數,那么該怎么辦呢?
我想實現這樣的目標:
Dictionary<Action, object[]> paramsForAction = new Dictionary<Action, object[]>();
public void ExecuteInUpdate(Action _action, params object[] _args)
{
paramsForAction.Add(action, args);//save params for action
//add action to queue
}
public void Update()
{
//find action to execute
object[] args = paramsForAction[actionToExecute];//get params for action
actionToExecute(args);
}
當然這是行不通的,沒有任何意義,但是希望您能得到我正在嘗試做的事情。
只需將您的方法調用包裝在lambda表達式中即可:
Action act = () => MethodCalledNotInUnityThread1(argVal1, argVal2); ExecuteInUpdate(act);
您也可以只使用Action<T>
,其中T
是方法的第一個參數。 然后還有兩個參數的Action<T1, T2>
等。
如果要返回類型,則Func<TResult>
是完全相同的主意,但具有類型的返回類型。 Func<TResult, TParam1>
等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.