Unity,从不同线程调用 Resources.Load

Unity, Calling Resources.Load from a different thread

我制作了一个要在游戏中实例化的预制件。

但是因为我希望它被实例化"behind the scene",这意味着,创建所有这些预制件的多个副本"while the player is doing something else"。

所以我把生成预制件的代码放在"in another thread"。

但是 Unity 告诉我 "Load can only be called from the main thread."

我试图将代码移动到协程中,但不幸的是协程运行在 "main thread"!

或者我应该说,他们不执行多个协程 "parallely and concurrently"!

所以有人可以这么好心教我该怎么做吗!?

非常感谢!

代码:(以备不时之需,尽管我认为它没有任何用处)

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);
    }
}