- Home /
Question by
Anemun · May 13, 2014 at 09:40 AM ·
c#gameobjectnullreferenceexceptionarrays
NullReference when accessing GameObject in array (C#)
Hello! I am new to Unity and I need help. I try to instantiate a prefab into anto an array of GameObjects and then use it from that array. Here is my 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;
}
}
Probles is that I get an NullReferenceException error on 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)
What am I doing wrong?
Comment
Best Answer
Answer by P4blo · May 13, 2014 at 09:50 AM
Hi! "name" is a property of Gameobject, and you are instantiating a Transform.
Change
public Transform somePrefab;
by:
public GameObject somePrefab;
or change this:
testArray [i] = Instantiate (somePrefab) as GameObject;
by this:
testArray [i] = Instantiate (somePrefab.gameObject) as GameObject;
Yeah, that works, thanks!! I thought that "as GameObject" will be enough to store Transform into GameObject array.