我场景中的一个脚本涉及创建立方体网格。这个过程确实需要相当长的时间,我一直在尝试在不导致 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/