C#在Unity游戏开发中进行多线程编程的方法

2019-12-30 12:21:47王冬梅

UnityEngine定义的基本类型的函数可以在分线程运行
Unity多线程插件

LOOM Multi Threading Framework 1.7 

核心方法


// Unlike "StartMultithreadedWorkloadExecution", you will have to build your own IThreadWorkerObject.
 // Downside: It requires some extra work. Upside: you got more controll over what goes in and comes out
 // Infact: You can create you own polymorphed IThreadWorkerObject-array, each ellement being a completely different type. For example: the statemachines of enemies are IThreadWorkerObject's and the array contains completely different classes with enemies/AI-behaviours.
 // < param name="workerObjects">An array of IThreadWorkerObject objects to be handled by the threads. If you want multiple cores/threads to be active, make sure that the number of IThreadWorkerObject's proves matches/exeeds your preferred number maxWorkingThreads. < /param>
 // < param name="onComplete">Fired when all re-packaged workLoad-objects are finished computing< /param>
 // < param name="onPackageExecuted">Fires foreach finished re-packaged set of workLoad-object< /param>
 // < param name="maxThreads"> Lets you choose how many threads will be run simultaneously by the threadpool. Default: -1 == number of cores minus one, to make sure the MainThread has at least one core to run on. (quadcore == 1 core Mainthread, 3 cores used by the ThreadPoolScheduler)< /param>
 // < param name="scheduler">If Null, a new ThreadPoolScheduler will be instantiated.< /param>
 // < param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace< /param>
 // < returns>A ThreadPoolScheduler that handles all the repackaged workLoad-Objects< /returns>
 public static ThreadPoolScheduler StartMultithreadedWorkerObjects(IThreadWorkerObject[] workerObjects, ThreadPoolSchedulerEvent onCompleteCallBack, ThreadedWorkCompleteEvent onPackageExecuted = null, int maxThreads = -1, ThreadPoolScheduler scheduler = null, bool safeMode = true)
{
  if (scheduler == null)
  scheduler = CreateThreadPoolScheduler();

 scheduler.StartASyncThreads(workerObjects, onCompleteCallBack, onPackageExecuted, maxThreads, safeMode);
 return scheduler;
}

 

结束语

Unity可以使用多线程,但对其有很多限制,所以在不使用UnityEngine API的情况下,可以使用多线程,提高多核CPU的使用率。通常可以将需要大量计算的算法内容,放置到多线程中执行,包括逻辑框架也可以放到多线程中执行。本篇理论性较强,后期会陆续发布实战型文章。



注:相关教程知识阅读请移步到c#教程频道。