C# get transform of another GameObject

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);

1 Like

that should work, try

GameObject temp = GameObject.Find(“house”);
Transform houseTransform = temp.GetComponent();

2 Likes

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)

var houseTransform : Transform;

function GetHouseTransform(){
    GameObject go = GameObject.Find("house");
    if (go != null){
        houseTransform = go.transform
    } else {
        Debug.Log("House not found");
    }
}

C#

Transform houseTransform;

void GetHouseTransform(){
    GameObject go = GameObject.Find("house");
    if (go != null){
        houseTransform = go.transform
    } else {
        Debug.Log("House not found");
    }
}
1 Like

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.

Yes, thanks

easiest way is,
houseTransform = GameObject.Find(“house”).GetComponent();

This is bad on many levels, necro post, doesn’t add anything new or useful to the thread and most importantly, isn’t the ‘best’ way. See the third post for a better answer (if you must use GameObject.Find()).

2 Likes