- Home /
Return reference to object added to an array (Javascript)
I have a very simple issue. I'm adding an object and trying to return a reference to that object using the following code...
public var pages: Page[];
public function AddPage (obj : Page) {
pages += [obj];
return pages[pages.Length-1]; //return handle to object
}
Now I call this like so
var myTestPage = myAdventure.AddPage( new Page("testPage") );
and get this error
Object reference not set to the instance of an object.
Now there doesn't seem to be any issue with the construction of the object as calling AddPage without assigning to an object works fine and can be referenced perfectly.
Many thanks in advance!
Answer by Eric5h5 · Sep 23, 2014 at 10:08 PM
Arrays are fixed-length and can't have items added to them. Use a generic List instead.
Fixed-length? Does that mean once I have declared an array I cannot add or remove items from it?
Ah O$$anonymous$$ found some good reference material here -> http://wiki.unity3d.com/index.php?title=Which_$$anonymous$$ind_Of_Array_Or_Collection_Should_I_Use%3F
Thanks for the help!
Edit. It Works! Thanks (need to declare my list using constructor)
public var pages : List.<Page> = new List.<Page>();
public function AddPage (obj : Page) {
pages.Add(obj);
Debug.Log(pages.Count);
return pages[pages.Count-1]; //return handle to object
}
Just so you know, the function is returning the exact same object that you're adding, so there doesn't seem to be much point to having the function return anything.
O$$anonymous$$ One more question in regards to this
return pages[pages.Count-1]; isn't working, its not returning the object.