How to add instantiated gameobject to a list?

Never used a list before so i’m not sure what to do.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SS_Control : MonoBehaviour {

    public GameObject[] enemy;

    public float enemyCount;
    public float range;

    List<GameObject> enemies = new List<GameObject>();

    private float x,y,z;

    void Start ()
    {
        for (float i = 0; i < enemyCount; i++)
        {
            x = Random.Range (-range, range);
            y = Random.Range (-range, range);
            z = Random.Range (-range, range);

            Instantiate (enemy[Random.Range(0, enemy.Length)], new Vector3 (x, y, z), Quaternion.identity);
        }
    }
}
1 Like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SS_Control : MonoBehaviour {
    public GameObject[] enemy;
    public float enemyCount;
    public float range;
    List<GameObject> enemies = new List<GameObject>();
    private float x,y,z;
    void Start ()
    {
        for (float i = 0; i < enemyCount; i++)
        {
            x = Random.Range (-range, range);
            y = Random.Range (-range, range);
            z = Random.Range (-range, range);
            GameObject newGO = (GameObject)Instantiate (enemy[Random.Range(0, enemy.Length)], new Vector3 (x, y, z), Quaternion.identity);
            enemies.Add(newGO);
        }
    }
}

You must assign the instantiated enemy to a variable of type GameObject and cast it to such.
Then simply add it to the enemies list using the Add() method.

4 Likes

Thanks a lot!