Unity,调用资源。从其他线程加载

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

但是因为我希望可以在“幕后”实例化它,这意味着在“玩家正在做其他事情时”创建所有这些预制件的多个副本。

因此,我将生成预制件的代码放在了另一个线程中。

但是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);
    }
}
riijlcvyp 回答:Unity,调用资源。从其他线程加载

我无法测试此代码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,with a coroutine
    for(int i=0;i<1000;i++)
    {
        GameObject RaceGO = Instantaite(Race);
        RaceGO.transform.SetParent(Content);
    }
}
本文链接:https://www.f2er.com/3152527.html

大家都在问