Search Unity

Collecting data from children

Discussion in 'Scripting' started by skyhawk, Aug 26, 2007.

  1. skyhawk

    skyhawk

    Joined:
    Jun 13, 2005
    Posts:
    49
    (using C#)
    So I have a class IcarusBaseObject with a variable uint Health;

    How would I retrieve the Health of all children who have an IcarusBaseObject?
     
  2. Jonathan Czeck

    Jonathan Czeck

    Joined:
    Mar 17, 2005
    Posts:
    1,713
    Code (csharp):
    1. foreach (IcarusBaseObject ibo in GetComponentsInChildren(typeof(IcarusBaseObject))) {
    2.     Debug.Log(ibo.Health);
    3. }
    Note that it'll also print the Health of object the script this is attached to, if it has IcarusBaseObject. You can ignore that by something like...

    if (ibo.gameObject != gameObject)
    ...

    Cheers,
    -Jon
     
  3. VeganApps

    VeganApps

    Joined:
    Jun 30, 2006
    Posts:
    263
    First create a property for your health in the IcarusBaseObject script:

    Code (csharp):
    1.  
    2. private uint health;
    3.  
    4. public uint Health
    5. {
    6.    get { return health; }
    7.    set { health = value; } //if you also need a set
    8. }
    9.  
    Now get and reference to all gameObjects with a IcarusBaseObject script:

    Code (csharp):
    1.  
    2. Component[] icarusBaseArray;
    3. icarusBaseArray = gameObject.GetComponentsInChildren( typeof(IcarusBaseObject) ) as Component[];
    4.  
    Then run through the array in the parent:
    Code (csharp):
    1.  
    2. foreach ( IcarusBaseObject icarusBase in icarusBaseArray )
    3. {
    4.    uint retrievedHealth = icarusBase.Health;
    5.    // do something with retrievedHealth...
    6. }
    7.  
    EDIT: Harrr... Jonathan was faster... :)
     
  4. skyhawk

    skyhawk

    Joined:
    Jun 13, 2005
    Posts:
    49
    ahh, I see what I did wrong. I needed to do typeof(IcarusBaseObject)

    By the way, ALL THESE REFERENCES TO ICARUS ARE JUST COINCIDENCES I SWEAR :wink:
     
  5. skyhawk

    skyhawk

    Joined:
    Jun 13, 2005
    Posts:
    49
    My solution. Should give me what I want. Recursion is scary.
    Code (csharp):
    1.  
    2. public uint getTotalHealth()
    3.     {
    4.         uint tHealth = getHealth();
    5.         Component[] AllHealths = GetComponentsInChildren(typeof(IcarusBaseObject));
    6.         foreach(IcarusBaseObject x in AllHealths)
    7.         {
    8.             // don't include ourselves, or we infinitely recurse
    9.             if(x.gameObject != gameObject)
    10.                 tHealth+=x.getTotalHealth();
    11.         }
    12.         return tHealth;
    13.     }
    14.