(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?
Code (csharp): foreach (IcarusBaseObject ibo in GetComponentsInChildren(typeof(IcarusBaseObject))) { Debug.Log(ibo.Health); } 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
First create a property for your health in the IcarusBaseObject script: Code (csharp): private uint health; public uint Health { get { return health; } set { health = value; } //if you also need a set } Now get and reference to all gameObjects with a IcarusBaseObject script: Code (csharp): Component[] icarusBaseArray; icarusBaseArray = gameObject.GetComponentsInChildren( typeof(IcarusBaseObject) ) as Component[]; Then run through the array in the parent: Code (csharp): foreach ( IcarusBaseObject icarusBase in icarusBaseArray ) { uint retrievedHealth = icarusBase.Health; // do something with retrievedHealth... } EDIT: Harrr... Jonathan was faster...
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:
My solution. Should give me what I want. Recursion is scary. Code (csharp): public uint getTotalHealth() { uint tHealth = getHealth(); Component[] AllHealths = GetComponentsInChildren(typeof(IcarusBaseObject)); foreach(IcarusBaseObject x in AllHealths) { // don't include ourselves, or we infinitely recurse if(x.gameObject != gameObject) tHealth+=x.getTotalHealth(); } return tHealth; }