Declaration of variables in monobehaviour, and passing variables to update()

So I wanted at first to declare some constant in MonoBehaviour and use it to declare an array at the same time, which gives a weird error!

public class Q1: MonoBehaviour {

    public int n=1;
    int[] T = new int [n];
}

I coded a lot before, but why this way of deceleration is invalid? it looks totally correct, or is it something with how MonoBehaviour work?

To solve this problem, it seems that I need to declare and set my array inside a/the method, so I tried to use Awake() to set the array.

public class Q1: MonoBehaviour {

    public int n=1;

    void Awake(){
         int[] T = new int [n];
    }

    void Update(){
        Debug.Log(T[0]);
    }
}

The problem is that anything declared in awake or start or any other method is destroyed once it is finished!. which makes it impossible to use this solution especially since I want to change the value of the arrays T at run time in Update()!

So, I have to questions:

First: Why cant I declare and use the variable inside MonoBehaviour directly?
Second: Is it possible to pass variables from Awake() or Start() to Update() ?

So a few things.

n is not a true constant in your example.

const int n = 1; // this is constant

You’re mixing up declaration and assignment. They don’t have to go together;

int[] ints;

void Start()
{
    ints = new int[n];
}
2 Likes

Just to add, declaring a variable in any method means you can’t access it outside of that method(this has nothing to do with Awake and Start). You might want to read up on variable scopes. It looks like Unity even has a tutorial on it. Scope and Access Modifiers - Unity Learn

I usually code with C++, there is no way to declare an array without assigning dimensions to it.

Thanks

Declaring a variable at the class level then initializing it in Awake is a super common pattern in Unity.

If you aren’t using MonoBehaviours you can do the same thing with a constructor.

1 Like