Search Unity

object at root of a hierarchy

Discussion in 'Scripting' started by Ryuuguu, Sep 27, 2007.

  1. Ryuuguu

    Ryuuguu

    Joined:
    Apr 14, 2007
    Posts:
    391
    I have hierarchy with a camera at the top. When I do
    Code (csharp):
    1.         temp as duck
    2.         Debug.Log(transform.root)
    3.         temp = transform.root
    4.         Debug.Log(temp)
    5.         Debug.Log(temp.WorldToViewportPoint(transform.position))
    6.  
    (temp as duck is just boo's way making an untyped variable)
    temp is the transform attached to the camera. I would like to get the object ( a camera) that the transform is attached to. So I can use WorldToViewportPoint method.

    The above code fails because temp is a transform not the object the transform is attached to. I also tried temp = transform.root.parent but it has no effect.

    Is there a way to get the object a transform is attached to?
     
  2. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661
    I think what you are looking for is the inherited gameObject class.

    whatever.transform.gameObject;

    -Jeremy
     
  3. Ryuuguu

    Ryuuguu

    Joined:
    Apr 14, 2007
    Posts:
    391
    Thanks.

    I tried
    Code (csharp):
    1.         temp as duck
    2.         Debug.Log(transform.root)
    3.         temp = transform.root.gameObject
    4.         Debug.Log(temp.name)
    5.         Debug.Log(temp.WorldToViewportPoint(transform.position))
    6.  
    but at runtime it still can not find method WorldToViewportPoint. The name printed out is the cameras name.
     
  4. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661
    That's because GameObject doesn't have a WorldToViewPortPoint function. That function is in the camera class.

    You need transform.root.gameObject.camera;

    -Jeremy
     
  5. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    In that case you can skip .gameObject and just use transform.root.camera
     
  6. Ryuuguu

    Ryuuguu

    Joined:
    Apr 14, 2007
    Posts:
    391
    Thanks both those work. When I look at inspector it is obvious that when I choose create camera, I create a gameObject that has a camera and a transform attached. I guess the using x.camera instead of x.gameObject.camera is a convience shortcut

    Cheers
    Grant
     
  7. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661
    Np. If you look at the script reference for the class in question, you can see what members and methods are inherited from other base classes. Saves you doing GetComponent and such yourself when you really dont need to.

    -Jeremy