【发布时间】:2019-08-17 00:41:59
【问题描述】:
我想以某种方式从异步线程更改游戏对象。我需要保留侦听器/接口架构。
下面我创建了一个我当前实现的简单示例。
主脚本:
using UnityEngine;
public class MyScript : MonoBehaviour, IMyComponentListener
{
public GameObject cube;
private MyComponent _myComponent;
private void Start()
{
_myComponent = new MyComponent(this);
}
public void OnThreadCompleted()
{
cube.transform.Rotate(Vector3.up, 10f);
}
}
线程脚本:
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);
_listener.OnThreadCompleted();
}
}
监听器接口:
public interface IMyComponentListener
{
void OnThreadCompleted();
}
如果我尝试此代码,我将面临以下错误:
get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.GameObject:get_transform()
MyScript:OnThreadCompleted() (at Assets/Scripts/MyScript.cs:18)
MyComponent:Run() (at Assets/Scripts/MyComponent.cs:20)
很明显,我无法从异步线程更改主线程元素,但我该如何解决它或正确实现支持此功能的架构?
【问题讨论】:
-
也许coroutines 会解决你的问题。如果没有,你可以看看闪亮的新 job system
标签: c# multithreading unity3d interface listener