Search Unity

(C#) Dealing with GameObjects that are also member of custom classes

Discussion in 'Scripting' started by JordanC, Feb 12, 2016.

  1. JordanC

    JordanC

    Joined:
    Mar 3, 2014
    Posts:
    2
    I've created a List of type <Enemy> that contains the Enemies in my game.

    Class Enemy is an abstract superclass that inherits from Monobehavior and implements ITakeTurns, and by doing so I've guaranteed that every Enemy has a method called turn().

    Each Enemy is a GameObject, as well, and currently there is only one type, but I'm trying to create a flexible framework so that I can add different enemies later.

    However, I'm having trouble as for some reason my list shows the objects as "null" and I'm sure I'm doing something wrong. Here is the relevant code:

    Code (CSharp):
    1. Enemy e = Instantiate (enemy, cell, Quaternion.identity) as Enemy;
    2. enemies.Add(e);
    The enemies DO get added to the game, but later when I iterate through the list the items are null. I want to be able to iterate through a list of enemies and call their turn() method.

    I ran this code as a test, and it just says "null" for each item in the List:

    Code (CSharp):
    1.         foreach (Enemy i in enemies)
    2.         {
    3.             Debug.Log (i);
    4.         }
    I've been stuck for hours and any help would really be appreciated!!!
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    Here:
    Code (csharp):
    1.  
    2. Enemy e =Instantiate(enemy, cell, Quaternion.identity)as Enemy;
    3.  
    What type is 'enemy'? I'm betting GameObject?

    This means the cloned object that is returned is going to be of type GameObject, and you can't convert a GameObject to Enemy with the 'as' operator.

    The 'Enemy' class isn't a GameObject, it's a component attached to a GameObject. Try something more like:

    Code (csharp):
    1.  
    2. var go = Instantiate(enemy, cell, Quaternion.identity) as GameObject;
    3. Enemey e = e.GetComponent<Enemy>();
    4. enemies.Add(e);
    5.  
     
  3. JordanC

    JordanC

    Joined:
    Mar 3, 2014
    Posts:
    2
    Enemy is an abstract superclass that inherits from Monobehavior. Class Enemy is in a script on its own that is not attached to anything. The actual object I'm trying to create is an object of on of Enemy's subclasses, EvilRedSphere. I set it up this way so that when I have more than one type of Enemy, I can still iterate through a List and know that every member has a Turn() method.

    I'm new to Unity but I'm used to other environments where I have always set it up this way. Maybe I''m missing a big-picture idea and not setting it up in a way that Unity supports.

    So I guess maybe the answer I'm looking for is a different way of setting up this functionality. I know how to do what I'm trying to do in Java but maybe it's the wrong approach for Unity/C#