Update UI from inside a loop

Hi
i have this really slow for-loop which creates prefabs and materials using code.
I would like to have a UI text field update and show the loop iteration,
Unfortunately the for loop exits only once its finished and the UI text does not update in the UI field although I change its .text property in the for loop.

I suspect that this is happening because the Update() function is not called, because of the blocking inside the loop.

Is there a way to force update the UI from inside the for-loop, in order to have it show the loop iterations.

Thanks
Dimi

Unless you run the loop in a separate thread, the update function cannot be called, because the processor is busy running your loop. The only way around this would be to STOP processing the loop after a certain period of time/number of iterations, then resume during the NEXT update cycle. This would give Update a chance to redraw new values, like the last iteration count, to the screen.

change the order of code currentColor = GetTextureColorsScript.GetColors(); GetTextureColorsScript = GetComponent<ChangeTexture>(); to GetTextureColorsScript = GetComponent<ChangeTexture>(); currentColor = GetTextureColorsScript.GetColors(); because you have not assign GetTextureColorsScript to your variant, so you got null exception

2 Answers

2

use a coroutine and yield at the end of each iteration.

Sorry for the different naming: GetTextureColorsScript = GetComponent(); It is actually: ChangeTextureScript = GetComponent(); That is a good hint! Thank you! Unfortunately a new Exeption appears. NullReferenceException: Object reference not set to an instance of an object DrawPrimitives.GeneratePrimitives () (at Assets/nuilab/Scripts/DrawPrimitives.cs:35) DrawPrimitives.Start () (at Assets/nuilab/Scripts/DrawPrimitives.cs:18)

I used a coroutine and reworked my code for this.
Using threads is also a possibility probably but coding a coroutine is faster.
Thanks for all the answers.

I see nothing in your line 35

35 rend.sharedMaterial.shader = Shader.Find("Cube_Material");