Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

Discussion in 'Scripting' started by QassimUnity2, Jul 24, 2017.

  1. QassimUnity2

    QassimUnity2

    Joined:
    Jul 8, 2017
    Posts:
    2
    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!

    Code (CSharp):
    1. public class Q1: MonoBehaviour {
    2.  
    3.     public int n=1;
    4.     int[] T = new int [n];
    5. }
    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.

    Code (CSharp):
    1. public class Q1: MonoBehaviour {
    2.  
    3.     public int n=1;
    4.  
    5.     void Awake(){
    6.          int[] T = new int [n];
    7.     }
    8.  
    9.     void Update(){
    10.         Debug.Log(T[0]);
    11.     }
    12. }

    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() ?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    So a few things.

    n is not a true constant in your example.
    Code (csharp):
    1.  
    2. const int n = 1; // this is constant
    3.  
    You're mixing up declaration and assignment. They don't have to go together;
    Code (csharp):
    1.  
    2. int[] ints;
    3.  
    4. void Start()
    5. {
    6.     ints = new int[n];
    7. }
    8.  
     
    Kiwasi and QassimUnity2 like this.
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
  4. QassimUnity2

    QassimUnity2

    Joined:
    Jul 8, 2017
    Posts:
    2
    I usually code with C++, there is no way to declare an array without assigning dimensions to it.

    Thanks
     
  5. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    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.
     
    KelsoMRK likes this.