Getting child object of gameObject in unity

David picture David · Mar 1, 2016 · Viewed 11.5k times · Source

I have Object "Unit" with sub Objects "Monster and Health. I also have Object Tower that has sphere collider. Also I have OnTriggerEnter(Collider co) function in Tower Object that detects Unit.

When it does I can for example print the name "Unit" by accessing it co.gameObject.name, or even co.name, which I guess is the same.

But how can I get the first subobject of unit for example. I mean Monster object, but not by name but just the FIRST SUB OBJECT of Unit object ?

UPDATE

Using this code:

void OnTriggerEnter(Collider co)
{
    Debug.Log(co.gameObject.transform.GetChild(0));
}

Causes an exception:

UnityException: Transform child out of bounds
Tower.OnTriggerEnter (UnityEngine.Collider co) (at Assets/Scripts/Tower.cs:19)

UPDATE 2 print(co.transform.childCount); gives 2

And that's correct cause I have

Unit
>

Monster

HealthBar

subobjects

Update 3 Tower code. using UnityEngine; using System.Collections;

public class Tower : MonoBehaviour
{
    // The Bullet
    public GameObject Bullet;

    // Rotation Speed
    public float rotationSpeed = 35;

    void Update()
    {
        transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed, Space.World);
    }

    void OnTriggerEnter(Collider co)
    {

        print(co.transform.childCount);

        if (co.gameObject.name == "Unit(Clone)")
        { 

            GameObject g = (GameObject)Instantiate(Bullet, transform.position, Quaternion.identity);
            g.GetComponent<Bullet>().target = co.transform;
        }
    }
}

This Code Somehow manages to print twice

2
UnityEngine.MonoBehaviour:print(Object)
Tower:OnTriggerEnter(Collider) (at Assets/Scripts/Tower.cs:20)
0
UnityEngine.MonoBehaviour:print(Object)
Tower:OnTriggerEnter(Collider) (at Assets/Scripts/Tower.cs:20)

Answer

MarengoHue picture MarengoHue · Mar 1, 2016

You'll have to operate on GameObject's transform. You can use Transform.GetChild(int index) function.

You will probably first have to check if there are any children because GetChild throws exceptions if you get out of bounds of the array. For that you'll have to use Transform.childCount.

More info can be found here:

http://docs.unity3d.com/ScriptReference/Transform.GetChild.html http://docs.unity3d.com/ScriptReference/Transform-childCount.html