Search Unity

Accessing parent game object and storing as a variable

Discussion in 'Scripting' started by Ultermarto, Jan 4, 2014.

  1. Ultermarto

    Ultermarto

    Joined:
    May 10, 2013
    Posts:
    31
    I'm trying to get an object's animation to play if a box collider trigger, which is the child of said object, gets hit by the player. Try as I might, I can't successfully assign the parent object to my variable without using GameObject.Find, which I don't want to use. I've been trying to use transform.parent.gameObject, but my console just keeps telling me that the variable is unassigned.

    Code (csharp):
    1. function OnTriggerEnter (collider : Collider)
    2. {
    3.     var treasureChest : GameObject = transform.parent.gamObject;
    4.     treasureChest.animation.Play();
    5. }
    Here's my code.

    The objects in question are a treasure chest (the parent) with an animation which I want to play, and a child box collider, to which this trigger script is attached.
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    gamObject != gameObject
     
  3. tux83

    tux83

    Joined:
    Jan 2, 2014
    Posts:
    19
    hi, you can use the collider children

    in this method(c#):


    Code (csharp):
    1.  GameObject sample = obj.collider.gameObject.transform.parent.parent.gameObject
    Debug name:

    Code (csharp):
    1. Debug.Log("GameObject Parent: "+ sample.name);
    in Java, i think so:

    Code (csharp):
    1.  
    2. function OnTriggerEnter (collider : Collider)
    3.  
    4. {
    5.  
    6.     var treasureChest : GameObject =  collider.collider.gameObject.transform.parent.parent.gameObject;
    7.  
    8.     treasureChest.animation.Play();
    9.  
    10. }
    11.  
     
  4. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    Why do you have two GameObject parented to each other?
     
  5. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Sounds like exactly what you would want to do , so that the trigger volume moves with the chest object.
     
  6. Ultermarto

    Ultermarto

    Joined:
    May 10, 2013
    Posts:
    31
    I ... whu ...

    Argh. Thank you for your patience.
     
  7. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    Why is the trigger volume (component) not on the chest GameObject?