adding object to builtin array works in one script, not in another?


I’ve been using the builtin javascript array to keep together some gameobjects loading on startup.

while this is working:

var PiecesLibrary : GameObject[];
PiecesLibrary += [pieceGO];

in another script i’m doing exactly the same:

var connectorsArr : GameObject[];
function AddConnectorToList(){
	connectorsArr += [connectorToAdd];

i get “object reference not set to an instance of an object” when calling the function on the 2nd example!
connectorToAdd is a valid gameObject just like pieceGO, the only difference is i call this function from another script. this error is like there is no “initialisation” of the connectorsArr? but it works on the first script…

please don’t tell me to change built in arrays to lists the code is already quite complete and since it works with the first script i’d wish to see it work in the second one too…

thank you for your time!


ok, i will explain a bit better:

i build something like a lego assembly so i load some parts. for each part i have connection points as gameObjects (which i use later to make joints) which i want to keep track in an array (and not hold them as children of the piece) . so i thought i’d attach a script to each piece (called “Pieces”) and keep that array in there. So i have the pieces script that i attach to each of the pieces when it’s created:

		var pieceGO:GameObject = new GameObject();
		var filter:MeshFilter = pieceGO.AddComponent(MeshFilter);
		var renderer:MeshRenderer = pieceGO.AddComponent(MeshRenderer);
		var collide:MeshCollider = pieceGO.AddComponent(MeshCollider);
		filter.mesh = Resources.Load(piecesDirectory+pieceName,Mesh);
		collide.sharedMesh =Resources.Load(collidersDirectory+pieceName,Mesh);
		var pieceScript = pieceGO.GetComponent("Pieces") as Pieces;

and this is the “pieces” script:

var Selected : boolean = false;
var highlighted : boolean = false;
var groupName : String = "";
var connectorsArr : GameObject[];

private var selectedMaterial:Material;

function Start(){

function Update(){
	if (Selected){
		gameObject.renderer.material = selectedMaterial;

function AddConnectorToList(connGO:GameObject){
	connectorsArr += [connGO];

all lines of the code work and load objects and everything works perfectly while this line
connectorsArr += [connGO];

returns an error: object reference not set to an instance of an object

Any new ideas?

the problem was really this like i sensed:

When attaching a script to a gameObject dynamically, the array values are not initialised so when trying to change them there is an error, unline the editor which i guess initialises them automatically.

so all i had to do is add a line to initialise it in my code

connectorsArr = new GameObject[0];

and then happily add stuff to it directly

connectorsArr += [connGO];

i hope this helps others!!