Search Unity

NullReferenceException with custom class

Discussion in 'Scripting' started by Dextozz, May 25, 2019.

  1. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    112
    Hi, probably missing something obvious but can't seem to get past this. Here's the code:

    Code (CSharp):
    1. public class TempClass : MonoBehaviour
    2. {
    3.     private MyClass[] objects;
    4.  
    5.     // Start is called before the first frame update
    6.     void Start()
    7.     {
    8.         objects = new MyClass[transform.childCount];
    9.  
    10.         for (int i = 0; i < objects.Length; i++)
    11.         {
    12.             objects[i].MyObjectTransform = transform.GetChild(i);
    13.             Debug.Log(objects[i].MyObjectTransform.name);
    14.         }
    15.     }
    16. }
    17.  
    18. internal class MyClass
    19. {
    20.     public Transform MyObjectTransform { get; set; }
    21. }
    The error is on the line "objects.MyObjectTransform = transform.GetChild(i);", any idea what I might be missing here?
     
  2. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    112
    Update:
    Yeah, I was missing something obvious. When I added this line of code to line 7 of my script, it worked.
    Code (CSharp):
    1. objects[i] = new MyClass();