我制作了一个要在游戏中实例化的预制件。
但是因为我希望可以在“幕后”实例化它,这意味着在播放器正在做其他事情的同时创建所有这些预制件副本。
所以我将生成预制的代码放在了另一个线程中。
但是Unity告诉我“只能从主线程调用Load。”
我试图将代码移入协程,但不幸的是协程在“主线程”中运行!
或者也许我应该说,它们不会“并行并发”地执行多个协程!
所以请别人这么好心,教我该怎么做!?
非常感谢!
代码:(如果需要,即使我认为这样做不会有任何好处)
void Start()
{
Thread t = new Thread(Do);
t.Start();
}
private void Do()
{
for(int i=0;i<1000;i++)
{
GameObject RaceGO = (GameObject)(Resources.Load("Race"));
RaceGO.transform.SetParent(Content);
}
}
我无法测试此代码atm,但我想您明白了。
GameObject raceGameObject;
// Start "Message" can be a coroutine
IEnumerator Start()
{
// Load the resource "Race" asynchronously
var request = Resources.LoadAsync<GameObject>("Race");
while(!request.IsDone) {
yield return request;
}
raceGameObject = request.asset;
Do();
}
private void Do()
{
// Instantiating 1000 gameobjects is nothing imo, if yes split it then, with a coroutine
for(int i=0;i<1000;i++)
{
GameObject RaceGO = Instantaite(raceGameObject);
RaceGO.transform.SetParent(Content);
}
}
此外,我也不建议您在编辑器中仅使public Gameobject myGameObj;
字段为其分配值,然后执行此操作:
// Assign this inside the editor
public GameObject Race;
void Start()
{
Do();
}
private void Do()
{
// Instantiating 1000 gameobjects is nothing imo, if yes split it then, with a coroutine
for(int i=0;i<1000;i++)
{
GameObject RaceGO = Instantaite(Race);
RaceGO.transform.SetParent(Content);
}
}