2 回答

TA貢獻1806條經(jīng)驗 獲得超8個贊
這只是一個例子,因為你要求它。
一般來說,UnityMainThreadDispatcher來自您的鏈接很好。
無論如何,它只是在一種Update方法中處理隊列。我不想使用這個 Singleton-Pattern 解決方案,而只是在MonoBehaviour您已有的組件中做同樣的事情(Singleton 在大多數(shù)情況下只是一個快速但骯臟的解決方案)
public class MyScript : MonoBehaviour, IMyComponentListener
{
public GameObject cube;
private MyComponent _myComponent;
private ConcurrentQueue<Action> callbacks = new ConcurrentQueue<Action>();
private void Start()
{
_myComponent = new MyComponent(this);
}
// Work the callbacks queue
private void Update()
{
if(callbacks.Count == 0) return;
while(callbacks.Count != 0)
{
Action a;
if(!callbacks.TryDequeue(out a)) continue;
a.Invoke();
}
}
public void ThreadCompleted()
{
callbacks.Enqueue(OnThreadCompleted);
}
private void OnThreadCompleted()
{
cube.transform.Rotate(Vector3.up, 10f);
}
}
而不是你會打電話enqueue給那個,而不是像
((MyScript)_listener).ThreadCompleted();
問題可能是這里的類型轉(zhuǎn)換..或者您可以將方法添加到接口。
如果您有多個偵聽器(似乎是由于界面),我也會使用您的方式,可能仍然沒有單例,而是使用適當?shù)囊茫缤ㄟ^ Inspector。
在我的智能手機上打字,所以沒有保修,但我希望我能表達清楚

TA貢獻1796條經(jīng)驗 獲得超4個贊
我想出了一個使用外部組件UnityMainThreadDispatcher的解決方法。
按照安裝說明進行操作后,我已將調(diào)度程序更新為以下示例并發(fā)揮了魅力!
線程腳本:
using System.Threading;
public class MyComponent
{
private readonly IMyComponentListener _listener;
public MyComponent(IMyComponentListener listener)
{
_listener = listener;
Thread myThread = new Thread(Run);
myThread.Start();
}
private void Run()
{
Thread.Sleep(1000);
UnityMainThreadDispatcher.Instance().Enqueue(() => _listener.OnThreadCompleted());
}
}
- 2 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報