- Home /
Null reference when accessing GameObject in the Array(C#)
Hello! I am new to Unity and I faced a problem with arrays. I create a prefab and try to instantiate it and store instances into my array. Here's the code:
public class TestScript : MonoBehaviour
{
public Transform somePrefab;
GameObject[] testArray;
void Start ()
{
testArray = new GameObject[5];
CreatingObjects ();
AssignNames ();
}
void CreatingObjects ()
{
for (int i = 0; i < 5; i++) {
testArray [i] = Instantiate (somePrefab) as GameObject;
}
}
void AssignNames ()
{
for (int i = 0; i < 5; i++)
testArray [i].name = "Cube # " + i;
}
}
Unity gives me NullReferenceException error at line 28 (23 here):
"NullReferenceException: Object reference not set to an instance of an object TestScript.AssignNames () (at Assets/Scripts/TestScript.cs:28) TestScript.Start () (at Assets/Scripts/TestScript.cs:14)"
For some reason I cannot access my stored GameObject at specific index. Unity creates 5 objects but i can't reach them.
Looks like i don't know something about Unity arrays but i cannot figure it out.
Answer by haim96 · May 13, 2014 at 09:35 AM
what if you change:
public Transform somePrefab;
to:
public Gameobject somePrefab;
Yeah, that works, thanks!! I thought that "as GameObject" will be enough to store Transform into GameObject array.
about assigning names - made it just for clarity, actually i'm not doing this =)
Your answer
Follow this Question
Related Questions
NullReference when accessing GameObject in array (C#) 1 Answer
node null reference 1 Answer
Distribute terrain in zones 3 Answers
Sorting gameobjects in an array c 2 Answers
NullReferenceException when trying to get Collider2D's parent gameObject 1 Answer