c# - 使用协程加载网格 - 等到完成,

标签 c# unity3d coroutine

我场景中的一个脚本涉及创建立方体网格。这个过程确实需要相当长的时间,我一直在尝试在不导致 Unity 变得无响应的情况下实现它。

目前的代码 - 有效 - 您可以在网格生成时观看。但是,场景中的其他脚本同时执行任务并导致异常(它们正在访问尚未创建的网格上的图 block )。

下面的脚本是唯一具有“唤醒”功能的脚本 - 其他脚本在第一个脚本完成唤醒之前执行“更新”和“OnGUI”。

 GridGenerator.cs

public GameObject[,] tiles = new GameObject[Constants.BOARD_WIDTH, Constants.BOARD_HEIGHT]; 
   // Run a double loop to create each tile.
    void Awake () 
    {
        StartCoroutine(doSetup());
    }

    IEnumerator doSetup()
    {
        yield return StartCoroutine (loadLevel());
        DoOtherStuff();
    }

    IEnumerator loadLevel()
    {   
        for (int i = 0; i < Constants.BOARD_WIDTH; i++)             
        {
            for (int j = 0; j < Constants.BOARD_HEIGHT; j++) 
            {
                tiles[i,j] = newTile();
                yield return(0);
            }
        }
    }

如何让 doOtherStuff() 方法等待协程完成?

我试过一个 bool 切换(卡住统一) 我试过使用锁(没用)

或者有更有效的方法吗?

编辑:代码在生成网格后成功完成 OtherStuff()。 doOtherStuff() 的一部分是将网格的引用传递给单独的类。 尝试在 Update 方法中访问网格时,单独的类抛出异常。这表明,更新方法在 GridGenerator.cs 中的 Awake 完成之前被调用。

最佳答案

最简单的方法是在另一个协程中启动你的协程,这样你就可以屈服于它:

void Awake () 
{
    StartCoroutine(doSetup());
}

IEnumerator doSetup ()
{
    yield return StartCoroutine(createGrid()); // will yield until createGrid is finished
    doOtherStuff();   
}

IEnumerator createGrid()
{   
        for (int i = 0; i < Constants.BOARD_WIDTH; i++)             
        {
            for (int j = 0; j < Constants.BOARD_HEIGHT; j++) 
            {
                // Instantiate a new tile 
                yield return(0);
            }
        }
    }
}

关于c# - 使用协程加载网格 - 等到完成,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30516639/

相关文章:

c# - Airconsole 和 Unity 集成问题

c# - 在 Update() 函数中完成后如何停止方法? - C# - Unity3D

android - Unity GoogleMobileAdsMediationTestSuite 抛出异常 setAdListener 必须在主 UI 线程上调用

kotlin - 何时在 Kotlin 中启动新范围

c++ - 在 Boost.Asio Stackful Coroutine 中产生

c# - 指南针 UI 和指针

c# - 为什么默认方法参数必须是 C# 中的编译时常量

c# - Topshelf:成功安装服务后安装命令没有返回

c++ - C++20 中的协程是什么?

c# - UnityContainer,子容器注入(inject)