Should we define variables in Update() ?

HI,

Here are some code snippets from the 2D sample:

Update(){
	// How high in world space should the camera look above the target?
	float heightOffset = 1.0f;
	// How much should we zoom the camera based on this target?
	float distanceModifier = 1.0f;
	// By default, we won't account for any target velocity in our calculations;
	float velocityLookAhead = 0.15f;
	Vector2 maxLookAhead = new Vector2(3.0f, 3.0f);

        ........
}

will this make unity slow down ? Should we move all definition of variables outside Update() ?

Thanks .

You should always put them outside of Update(), cause having them in there makes the varaible every update call, which is in most cases pretty inefficient

not necessarily true
http://forum.unity3d.com/threads/92369-newbie-is-there-any-overhead-declaring-local-variables-inside-Update?highlight=measure+eric
http://forum.unity3d.com/threads/40981-it-is-good-to-declare-variable…if…

This is really only true if you are declaring a variable with a very complex constructor. For any simple data types (string/bool/int/float/vector/rect…) the performance impact is absolutely negligible when using local variables inside a function and, in fact, can perform better than using a global variable as tested by multiple people.

Realistically though, you have to be doing an incredible amount of declarations for there to even be a measurable difference - very, very unlikely in most game code within the update loop (and certainly far from the case with your 3 floats and a vector2).

Since the performance concern is legitimately negligible with any simple class or struct, your main focus should be on readability, maintainability, and proper scope - which all point to local variables within the update loop.

You should keep variables inside functions unless you have a really good reason not to. (Such as the variables needing to be accessed by other functions.)

–Eric

To elaborate further, ‘variables’ is a general term.

I try to initialize classes, like Transform as little as possible and keep them outside repetitive functions like Update(). Classes have to be cleaned up by the GC and can cause stutter issues after a certain point. Structs (and stuff like Single, Int are structs) should be initialized in the smallest scope possible - ie: function level, just to keep clutter to a minimum.