Instantiating GameObject and Adding to list

So like the title says I am trying to instantiate an GameObject and add it to a list, in this case it’s to manage the gameobjects because I do not want to many in my scene. Code:

void Start () {
        for(int x = 0; x < MaxAmountWolfs; x++)
        {
            GameObject wolf= Instantiate(Wolfs);
            Spawn.Random(wolf); // this is just another class that I use to give the object a random spawn location within the navmesh boundaries.

            lstWolfs.Add(new AIAnimal { Animal = wolf});
        }  
        Debug.Log(lstWolfs.Count);
        foreach(AIAnimal animal in lstWolfs)
        {
             Debug.Log(animal.name);
        }        
}

The objects spawn just fine and they appear in the hierarchy which is good. however when I debug the list all the objects are null… which makes absolutely no sense to me.

The class AIAnimal is simply:

public class AIAnimal : MonoBehaviour {
    public GameObject Animal { get; set; }
}

I probably making some stupid mistake, I just don’t see it.

This should work :

  void Start () {
      for(int x = 0; x < MaxAmountWolfs; x++) {
          GameObject wolf = Instantiate(Wolfs) as GameObject;  //Instantiante the wolf.
          lstWolfs.Add(wolf); //Add it to your list
          Spawn.Random(wolf); //Spawn it somewhere
          new AIAnimal { Animal = wolf} //Set the AI
      }
  }

Add the instantiated GameObject instead of the AI.

I havent tried that but that makes no sense, AIAnimal contains just set and get properties, and as soon as I spawn it it’s not null so why would it become null when I add it to the list. also the list is declared as :

List<AIAnimal> lstwolfs = new List<AIAnimal>();

So it expects an AIAnimal class, not just a gameobject… so adding wolf won’t work :slight_smile:

Using “new” for components is not recommended, you have to use GameObject.AddComponent method.

Something like this…

for(int x = 0; x < MaxAmountWolfs; x++)
{
    GameObject wolf= Instantiate(Wolfs);
    Spawn.Random(wolf);
    AIAnimal aiComponent = wolf.AddComponent<AIAnimal>();
    aiComponent.Animal = wolf;
    lstWolfs.Add(aiComponent);
}

Also, that “Animal” variable inside the AIAnimal class looks redundant… why not just use gameObject? Every MonoBehaviour has the “gameObject” field that’s a reference to the GameObject it’s attached.