Search Unity

  1. We would like to hear your feedback about Unity and our products. Click here for more information.
    Dismiss Notice

C# get transform of another GameObject

Discussion in 'Scripting' started by Jason210, Apr 6, 2013.

  1. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    127
    I want to access the transform of GameObject (a) from within the script attached to GameObject (b), and put it in a variable.

    Seems easy but I can't do it.

    I tried:

    temp = GameObject.Find("house");
    houseTransform = temp.GetComponent(Transform);
     
  2. jister

    jister

    Joined:
    Oct 9, 2009
    Posts:
    1,656
    that should work, try

    GameObject temp = GameObject.Find("house");
    Transform houseTransform = temp.GetComponent<Transform>();
     
  3. EliteMossy

    EliteMossy

    Joined:
    Dec 2, 2012
    Posts:
    513
    You don't need to use GetComponent to get the transform, unity has a very nice built in way to access it

    GameObject temp = GameObject.Find("house");

    then you can just reference temp.transform or cache it for later use via Transform houseTransform = temp.transform;

    Unityscript (JS)
    Code (csharp):
    1.  
    2. var houseTransform : Transform;
    3.  
    4. function GetHouseTransform(){
    5.     GameObject go = GameObject.Find("house");
    6.     if (go != null){
    7.         houseTransform = go.transform
    8.     } else {
    9.         Debug.Log("House not found");
    10.     }
    11. }
    12.  
    C#
    Code (csharp):
    1.  
    2. Transform houseTransform;
    3.  
    4. void GetHouseTransform(){
    5.     GameObject go = GameObject.Find("house");
    6.     if (go != null){
    7.         houseTransform = go.transform
    8.     } else {
    9.         Debug.Log("House not found");
    10.     }
    11. }
    12.  
     
    Last edited: Apr 6, 2013
  4. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    127
    Thanks both of you!

    Jister - It seems I was using the function - the generic one you used solved the problem.

    And thanks EliteMossy for the shortcut.