[SOLVED] For loop inside update()

Hello

I got a very basic question

I wrote a crosshair script where I can make changes to 4 individual reticles (left, right, top, bottom) where I can change size, thickness, colour of all 4 reticles through single attributes.

For this I used a for loop inside the update function to check the length ([4]) of the findByName(‘Crosshair).children. Since this is inside the update function I just wanted to know if this is a wrong way to do it? As the for loop is being called every frame constantly looping through the 4 child elements of the crosshair element. I currently do not have a UI menu to fire this in a function so I’m currently using it like this.

Hi @nasjarta,

You will want to avoid using findByName() in the update loop as it is very expensive. I would recommend defining the element you need in initialize() something like this.leftRet, this.rightRet, etc. Then you can use those values in the update loop without constantly having to search for them.

4 Likes

That makes sense - to only find it once rather than search for it every frame. From now on I will put similar elements inside init and reference them in update.

Thanks!