Search Unity

find child/parent of object instance

Discussion in 'Scripting' started by dacloo, Jun 23, 2006.

  1. dacloo

    dacloo

    Joined:
    Jun 30, 2005
    Posts:
    469
    Code (csharp):
    1. function Update () {
    2.    transform.Rotate(14,14,14);
    3.    }
    4.  
    5. function OnTriggerEnter (other : Collider) {
    6.    cirkel = gameObject.Find("cirkel");
    7.    cirkel.renderer.enabled = false;
    8.    Destroy(gameObject,1);
    9.    }
    10.  
    okay, this is what I am trying to achieve: GameObject is an
    prefab that is removed when the player touches it.
    The prefab contains a child object called 'cirkel'.
    I am trying to access this object. How?

    (My goal is to kill this child object 'cirkel' first, and a second later the object itself)
     
  2. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    Something like this:

    Code (csharp):
    1.  
    2. function FindChildByName(childName) {
    3.    for (var child : Transform in transform) {
    4.       if(child.name == childName)
    5.          return child.gameObject;
    6.    }
    7.    return null;
    8. }
    9.  
    Or even better, you could of course just use Transform.Find
    Code (csharp):
    1.  
    2.    child=transform.Find("cirkel");
    3.  
     
  3. dacloo

    dacloo

    Joined:
    Jun 30, 2005
    Posts:
    469
    Hi Freyr, thanks, I'll try it.

    The problem is that Find() does find a lot of results (because every prefab contains the same names), but it's about the *instance* I want to find.
     
  4. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    That's why you should use transform.Find and not GameObject.Find. Transform.Find is relative to the transform hierarchy, whereas GameObject.Find is a static method that searches the entire scene.
     
  5. dacloo

    dacloo

    Joined:
    Jun 30, 2005
    Posts:
    469
    :eek: I never knew this.

    This should be in a FAQ or tutorial, because IMHO it easily missed.
    Or perhaps I'm just being stoopid :)

    Thanks! Much appreciated.