Grid loading with coroutine - wait until the end,

One of the scenarios of my scene involves creating a grid of cubes. The process takes a lot of time, and I'm trying to implement it without causing Unity to not respond.

Currently, the code is working - you can observe the creation of the grid. However, other scenarios on the stage perform their tasks simultaneously and raise exceptions (they refer to tiles on the grid that have not yet been created).

Below is a script only a script that has the "Awake" function - other scripts perform "Update" and "OnGUI" before the first script has completed its awakening.

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

How do I make the doOtherStuff () method until the joint procedure is completed?

I tried a logical switch (which froze unity) I tried to use a lock (which did not work)

Or is there a more efficient way to do this?

EDIT: code successfully exits OtherStuff () after meshing. In addition to doOtherStuff (), you need to pass the grid link to a separate class. A separate class throws an exception when trying to access the grid in the Update method. It follows that the update method is called before Awake in GridGenerator.cs is completed.

+6
source share
1 answer

The easiest way is to run your coroutine in another coroutine so that you can give way to it:

 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); } } } } 
+1
source

Source: https://habr.com/ru/post/988120/


All Articles