Arrays in a class

Somehow this doesn’t work and can’t find a solution. (Unityscript)

#pragma strict

class Container {
    public var theItems = new Array();
}

private var myCont : Container[];

function Awake () {
    myCont = new Container[1];
   
    var someObject : GameObject = new GameObject("some");
   
    myCont[0].theItems.Add(someObject);
}

The last line gives an error (NullReferenceException).

You’ve declared myCont with a size of 1 which means it fills it with null items. You need to create a new Container instance, populate it, and add that to your array as well.

Thank you for the quick response. Unfortunately I don’t quite understand it.

Am I not creating a new container instance on line 11? Does this not create my array “theItems”, so I can access and populate it.

No. You’re creating an array of Containers with the size 1.

You’re creating the array, not the things in the array.

Ok. got it.
So this would be the correct approach?

#pragma strict

class Container {
    public var theItems = new Array();
}

private var myCont : Container[];

function Awake () {
    myCont = new Container[1];
  
    var c = new Container();
    var someObject : GameObject = new GameObject("some");
    c.theItems.Add(someObject);
      
    myCont[0] = c;
}

Yup - minus using UnityEngine.Array. They’re not type-safe, so better to use List instead.