If an Editor task is going to take more than half a second or so, then we should indicate progress complete/remaining to the user via a progress bar so that they understand that something is actually happening and the application has not crashed and frozen.
This recipe adds to the previous one, so make a copy of that project folder and do your work for this recipe with that copy.
To add a progress bar during the loop (and then remove it after the loop is complete), replace the PlacePrefabs()
method with the following code:
static void PlacePrefabs(){ string assetPath = "Assets/Prefabs/prefab_star.prefab"; starPrefab = (GameObject)AssetDatabase.LoadMainAssetAtPath(assetPath); int total = 100; for(int i = 0; i < total; i++){ CreateRandomInstance(); EditorUtility.DisplayProgressBar("Creating your starfield", i + "%", i/100f); } EditorUtility.ClearProgressBar(); }
As can be seen, inside the for
loop, we call the EditorUtility.DisplayProgressBar(...)
method, passing three parameters. The first is a string title for the progress bar dialog window, the second is a string to show below the bar itself (usually a percentage is sufficient), and the final parameter is a value between 0.0 and 1.0, indicating the percentage complete to be displayed.
Since we have loop variable i
that is a number from 1 to 100, we can display this integer followed by a percentage sign for our second parameter and just divide this number by 100 to get the decimal value needed to specify how much of the progress bar should be shown as completed. If the loop were running for some other number, we'd just divide the loop counter by the loop total to get our decimal progress value. Finally, after the loop has finished, we remove the progress bar with statement EditorUtility.ClearProgressBar()
.
18.191.147.77