多线程的工作往往是一种必要的罪恶。这就是我要做的是在一个Unity3D组件安全。当它是安全的时候,读取或更改其他组件的变量。例如,如果你试图修改或查询物理组件,你会遇到问题,同时一FixedUpdate发生了!这个组件使用互斥锁,让线程知道什么时候可以安全地使用其他游戏对象。
using System;
using System.Threading;
using UnityEngine;
public class ThreadedComponent : MonoBehaviour
{
Thread thread;
Mutex mainLoop;
void Awake() {
mainLoop = new Mutex(true);
thread = new Thread(ThreadWorker);
}
void Start() {
thread.Start();
}
void OnApplicationQuit() {
thread.Abort();
}
void ThreadWorker() {
//Catch and report any exceptions here,
//so that Unity doesn't crash!
try {
_ThreadWorker();
} catch(Exception e) {
if(!(e is ThreadAbortException))
Debug.LogError("Unexpected Death: " + e.ToString());
}
}
void Update() {
//Gives the thread a chance to work with gameobjects.
mainLoop.ReleaseMutex();
mainLoop.WaitOne();
}
void _ThreadWorker() {
while(true) {
//Play nice with other threads...
Thread.Sleep(0);
//Do random work here...
//Wait till it is safe to work with GameObjects.
mainLoop.WaitOne();
//Work with gameobject in here...
//But don't take too long!
mainLoop.ReleaseMutex();
//Signal Unity that we're done with GameObjects.
}
}
}
using System.Threading;
using UnityEngine;
public class ThreadedComponent : MonoBehaviour
{
Thread thread;
Mutex mainLoop;
void Awake() {
mainLoop = new Mutex(true);
thread = new Thread(ThreadWorker);
}
void Start() {
thread.Start();
}
void OnApplicationQuit() {
thread.Abort();
}
void ThreadWorker() {
//Catch and report any exceptions here,
//so that Unity doesn't crash!
try {
_ThreadWorker();
} catch(Exception e) {
if(!(e is ThreadAbortException))
Debug.LogError("Unexpected Death: " + e.ToString());
}
}
void Update() {
//Gives the thread a chance to work with gameobjects.
mainLoop.ReleaseMutex();
mainLoop.WaitOne();
}
void _ThreadWorker() {
while(true) {
//Play nice with other threads...
Thread.Sleep(0);
//Do random work here...
//Wait till it is safe to work with GameObjects.
mainLoop.WaitOne();
//Work with gameobject in here...
//But don't take too long!
mainLoop.ReleaseMutex();
//Signal Unity that we're done with GameObjects.
}
}
}