I read in the manual that its best to avoid memory allocations in Update functions. I understand what this means generally, don't create new textures every update, don't instantiate objects every update. But I wonder how intensely must you adhere to this?
Like for example I tend to do alot of
Vector3 newPos = transform.position; newPos.y += Time.deltaTime; transform.position = newPos
Should I not be doing something like that in update? Should I make like a temporary 'globalUtilityVector3' outside of the update loop, so then I don't have to create any temporary Vector3's to read in and out data?
I also do alot of
GUI.TintColor = new Color(1,1,1,.5);
should I not do that either? Should I declare a 'globalUtilityColor' outside of Update and then go
globalUtilityColor.a = .5; GUI.TinColor = globalUtilityColor;
asked May 16 '11 at 04:24 AM
You could/should store newPos , Color infos, etc in variables yes, and that would avoid creating it on each update. I don't know what kind of standard you should follow to write them but I use something like
EDIT: It seems that this is not important after all given all the comments, but without a proper bold statement from Unity in their docs ( haven't find one, but willing to learn!), I still prefer avoiding creating new variables inside function, when the function is called a lot during your game loop most likely). It might be unnecessary, yes, but I feel better like that with my current experience.
Actually, the Vector3 and globalUtilityColor won't do anything to your memory allocation. Since they are stack allocated, you will see zero memory allocation from them.
Rule of thumb:
I would say if you are debating creating a struct locally, DO IT. It will give you cleaner code. Looking at a long list of global variables that are only used inside of one specific function will confuse anyone who looks at your code.