Managing an Array of Objects

by Lance Gold

An Array can help manage numerous player feature and ability objects

Return to index

In this example, a Player ship object collects shields, fast motion, and triple shot firing.


public class PowerUp : MonoBehaviour
{
    // IDs for each Powerup prefab (each feature)
    [SerializeField]
    private int _powerupID;  // 0 for Triple Shot, 1 = Speed, 2 = Shield
...
}

To manage how these abilities are spawned, create a variable to contain them. Add the ‘[]’ to create a fixed list array — created before the game starts running.


public class SpawnManager : MonoBehaviour
{
    [SerializeField]
    private GameObject[] _powerup;
...
}

The included variables can be accessed as _powerup[0], _powerup[1] and _powerup[2]. Here is the Inspector for “Triple Shot Powerup” before beginning the rewrite as an array:

Inspector variables without using arrays

Inspector variables without using arrays

Now as an array, there is a drop down menu in the Inspector.

Powerup array appears as drop menu

Powerup array appears as drop menu

After entering ‘3’ into the array size:

Three unassigned Powerups

Three unassigned Powerups

Drag and drop two prefab objects to the array:

Array filled with references

Array filled with references

Now the array can be coded according to element.