Instantiating array/list of Prefabs

I want to generate prefabs from code and store pointers to control them individually as units in turn-based game.
I can do with with a bunch of vars but I’m having trouble getting it into an array or list.
Would this also be best done with a list if units rather than array were to be added/removed dynamically?

GameObject hero;
GameObject enemy01;
GameObject enemy02;
GameObject[] unitArray;

//THIS WORKS:
hero = (GameObject) Instantiate(Resources.Load("Hero", typeof(GameObject)), new Vector3(-2,1,0), Quaternion.identity);
enemy01 = (GameObject) Instantiate(Resources.Load("Enemy", typeof(GameObject)), new Vector3(2,1,0), Quaternion.identity);
enemy02 = (GameObject) Instantiate(Resources.Load("Enemy", typeof(GameObject)), new Vector3(3,1,2), Quaternion.identity);

//THROWS ERROR:
unitArray[0] = hero;

//THROWS ERROR:
unitArray[0] = (GameObject) Instantiate(Resources.Load("Hero", typeof(GameObject)), new Vector3(-2,1,0), Quaternion.identity);

Here’s the error:

Thankyou.

You have to initialize the array before you can use it.

–Eric

1 Like
unitArray = new GameObject[length];

You have define a size for the array to allocate o3o

This is not necessary for lists, their size is dynamic.

1 Like

Many thanks to both of you! :smile:

I feel like UnityScript (JS) is easier for noobs.
Especially since I can’t fully trust C# examples in official Scripting Reference. :face_with_spiral_eyes: