- Home /
best place to declare variables in the script
In one of Unity’s projects called Roll-a-Ball... http://unity3d.com/learn/tutorials/projects/roll-a-ball ...they declare the float moveHorizontal and moveVertical variables inside the FixedUpdate function. Like this:
public class PlayerControler : MonoBehaviour {
public float speed;
public GUIText countText;
public GUIText winText;
private int count;
...etc
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rigidbody.AddForce(movement * speed * Time.deltaTime);
}
Is it a good place? Isn’t the FixedUpdate declaring these variables on each fixed update? Wouldn’t it bebetter to declare those variables before the Start function is called? Like this:
public class PlayerControler : MonoBehaviour {
public float speed;
public GUIText countText;
public GUIText winText;
private int count;
private float moveHorizontal;
private float moveVertical;
...etc
void FixedUpdate()
{
moveHorizontal = Input.GetAxis ("Horizontal");
moveVertical = Input.GetAxis ("Vertical");
...etc
Variables declared inside function/method will be accesable only inside this function. If you wouldnt use those vars outside this method it's better that way.
Answer by whydoidoit · Feb 19, 2014 at 08:38 AM
No it's fine to declare it in the function. Declaration of variables that are local to a function allocates them on the stack by moving the stack pointer (done at compile time), it uses less memory as the variables are only temporary and has no performance hit.
Note that local variables are not initialized so they must be set before being read and will not have a default value. The compiler flags any attempt to use a local variable before setting its value.
so are you saying it is even better to declare them INSIDE the function? is it more resource efficient that way? requires less memory? and they are NOT being declared on each fixed update?
Yes that is what I am saying. They are being declared (space allocated on that stack each FixedUpdate) but as they are just simple variables this takes no extra time.
Also, it removes any possibilities of misused of the variable. Working as a $$anonymous$$m often leads to programmers not documenting enough. Then you put your two variables as global, and someone else comes to develop a method where for some reasons, he decides to use them, what you did is now all wrong.
As my rule of thumb, your program is like a zoo, each animal/variable is confined to his cage/scope, if you open it all, here comes the pain (including for the staff).
Answer by PaxForce · Feb 22, 2014 at 12:21 PM
I found a useful video that pretty much answers my question :) It is explained using C++ but it's easily applicable to C#.
Your answer
![](https://koobas.hobune.stream/wayback/20220613134014im_/https://answers.unity.com/themes/thub/images/avi.jpg)