在具有统一性的函数中实例化预制件
Instantiate a prefab in a function with unity
我正在尝试在我的场景中实例化一些预制件,我被迫在一个函数(而不是主线程)中执行它,因为我实例化了一个预制件仅当我通过 TCP 协议接收到一些数据时。
现在,我只是用立方体预制件进行测试,但它不起作用:
private void addAircraft(Plane plane)
{
listPlane.Add(plane);
//THIS 2 LINES ARE THE PROBLEM
GameObject cube = Instantiate(Resources.Load("Cube", typeof(GameObject))) as GameObject;
cube.transform.position = new Vector3((float)plane.X, 0, (float)plane.Y);
//
planeId_Object_Dictionnary.Add(plane.Flight, cube);
Debug.Log("Plane " + plane.Flight + " is added");
}
它 return 我 错误 :
Load 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.
即使很多人遇到过这个问题,我也找不到允许我在函数中实例化预制件的解决方案。
你可以有一个私人布尔检查器来查看是否应该随时添加飞机。当您收到 TCP 响应时将其标记为真,从 Update() 函数调用 addAircraft() 并再次将其标记为假。 Update() 在主线程上运行,因此这将确保 addAircraft() 也在主线程上运行。
我想如果你一直在等待,1 帧延迟也无所谓。
我正在尝试在我的场景中实例化一些预制件,我被迫在一个函数(而不是主线程)中执行它,因为我实例化了一个预制件仅当我通过 TCP 协议接收到一些数据时。
现在,我只是用立方体预制件进行测试,但它不起作用:
private void addAircraft(Plane plane)
{
listPlane.Add(plane);
//THIS 2 LINES ARE THE PROBLEM
GameObject cube = Instantiate(Resources.Load("Cube", typeof(GameObject))) as GameObject;
cube.transform.position = new Vector3((float)plane.X, 0, (float)plane.Y);
//
planeId_Object_Dictionnary.Add(plane.Flight, cube);
Debug.Log("Plane " + plane.Flight + " is added");
}
它 return 我 错误 :
Load 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.
即使很多人遇到过这个问题,我也找不到允许我在函数中实例化预制件的解决方案。
你可以有一个私人布尔检查器来查看是否应该随时添加飞机。当您收到 TCP 响应时将其标记为真,从 Update() 函数调用 addAircraft() 并再次将其标记为假。 Update() 在主线程上运行,因此这将确保 addAircraft() 也在主线程上运行。
我想如果你一直在等待,1 帧延迟也无所谓。