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

Getting a null object reference and I can't figure out why

Discussion in 'Scripting' started by KunoNoOni, Sep 14, 2017.

  1. KunoNoOni

    KunoNoOni

    Joined:
    Nov 16, 2013
    Posts:
    27
    I have 2 classes.

    public class A
    {
    public int foo;​
    }

    public class B : Monobehaviour
    {
    A[] myFoo = new A[8];

    void Start()
    {
    myFoo[0].foo = 1; //<====== This is the line that gives me the null object reference. Why?​
    }​
    }


    What am I missing?

    -KunoNoOni
     
  2. DaDonik

    DaDonik

    Joined:
    Jun 17, 2013
    Posts:
    258
    You have created an array of the size 8 which can hold instances of A. Now all entries of the array know which type they can hold, but they are still null.

    You can initialize the whole array like that:
    Code (CSharp):
    1. for (int i = 0; i < myFoo.Length; i++)
    2. {
    3.   myFoo[i] = new A();
    4. }
     
    makeshiftwings and Kurt-Dekker like this.
  3. KunoNoOni

    KunoNoOni

    Joined:
    Nov 16, 2013
    Posts:
    27
    Wow, thank you. I can't believe I made such a novice mistake :oops: