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 *= Instantiate (somePrefab) as GameObject; *
-
}*
-
}*
-
void AssignNames ()*
-
{*
-
for (int i = 0; i < 5; i++)*
_ testArray .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.