GameObject vs. Transform

Hi,
I am very new to Unity and C# and still learning and want to ask a real newbie question.

I have been thinking about the use of Transform vs GameObject when doing things like rotation etc. and realized that i do not fully understand when to use what.

Every object in a scene has a Transform. It’s used to store and manipulate the position, rotation and scale of the object. Every Transform can have a parent, which allows you to apply position, rotation and scale hierarchically.

As we all know there is also a .transform attached to a GameObject.

My very simple question is why and when do I want to use “Transform anObject” vs. “GameObject anObject”? I guess I can do the same thing with anObject that is attached to both of them, right?

Every GameObject has a transform (at least for now). If you want to change position or rotation of something, use Transform myOwnTransformName, since the transform of the gameobject has to be retrieved only once.
If you want other stuff, use GameObject myObject.
You can get the transform of a gameobject with myObject.transform, you can get the gameobject of a transform with transform.gameObject.

Just a matter of performance optimization which thing (Transform or GameObject) you will save for later use.

Actually this is not a question about Unity in specific, but about C#. C# allows you to make use of several objects which derive from certain classes. One class is “GameObject”, another class is “Transform”. The GameObject class has a property “transform” which is of class type “Transform” and may be accessed through the simple chaining operator like “.transform”.

Each class has different functionality, like the gameObject can be used to e.g. set something active or inactive and alike. The Transform class has properties which describe e.g. the position in a three dimensional space.

You might also create your own classes and attach them to your objects, e.g. a class “AI”, or “InputManager” or whatever you like. Still, they usually have different functionality. And that’s exactly where you decide which class you actually want to address, meaning the one which gives you the functionality needed. In your case, moving objects around, is only possible with the Transform class - not with the GameObject class.

“.transform” in the GameObject class only is a reference though to the Transform class of this specific gameObject.

Of course there are more details to that, but for a kick start that should help.

For more I strongly recommend having a look at object oriented programming basics first.

1 Like