- Home /
Question by
ashground · Jan 31, 2013 at 07:40 PM ·
javascriptgameobjectarrays
Once again, adding GameObjects to an array
This question seems to have been asked dozens of times all over the place, but for some reason I'm still having trouble with it.
I have several GameObjects (in the Hierarchy) called page_##, starting with page_00. I want to add these to an array.
This is my code:
static var currentPageNumber : int = 0;
static var totalPageCount : int = 5;
static var pageFinder : GameObject[];
function Start () {
var paddedPage : String;
var page : GameObject;
for(var i = 0; i < totalPageCount; i++) {
paddedPage = i.ToString("00");
page = GameObject.Find("page_"+paddedPage);
Debug.Log(page);
pageFinder[i] = page;
}
}
It makes it to the Debug.Log() just fine:
page_00 (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)
But when I try to add it to the array, I get an error:
NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)
What am I doing wrong? Do the pages have to be initiated somehow because they're in the Hierarchy and not dynamically generated?
Comment
Best Answer
Answer by Eric5h5 · Jan 31, 2013 at 09:27 PM
You haven't initialized the pageFinder array anywhere; you only declared the variable, so it's null.
Thank you. Luckily, I knew the size the array needed to be, so I fixed it with:
static var pageFinder : GameObject[] = new GameObject[totalPageCount];