C# --- Accessing Transform Component (noob question)

How do I access the Transform component of a game object in C#?

Here is what I have:

Transform sheepPosition = GameObject.GetComponent();

I have 2 errors:
“a new expression requires () or [ ] after type”
and
“expecting ‘;’”

Help?

It’s not a new Transform; it’s one that already exists. Take the word out.

Also, you probably don’t need GameObject., unless your script doesn’t derive from MonoBehaviour.

Alot of game objects already have the Transform component attached by nature. You can thus access the transform directly. Something like this,

GameObject go = new GameObject();

float x = 2.0f;
float y = 5.0f;
float z = 10.0f;

go.transform.position = new Vector3(x, y, z);

All of them do, unless you explicitly destroy it, which breaks everything, so don’t. :wink:

No, all that does is call GetComponent behind the scenes. Explicitly calling GetComponent<>() once, and storing a reference to that specific Transform, is a better method.

Yep, I bet that’s done in the GameObject’s constructor, that’s why once your game object is instantiated, you can call directly without using the GetComponent again.

No, that’s not what I said. If you don’t trust me, listen to Joachim state it in the section of the video corresponding to page 75.

http://unity3d.com/support/resources/unite-presentations/performance-optimization

Personally, I do it like this:

[HideInInspector] [SerializeField] new Transform transform;
#if UNITY_EDITOR
void Reset () {
	transform = GetComponent<Transform>();
}
#endif

And then I can use transform the same way as all of the examples show it.

Ok. but by far i have no problem accessing all the said members of transform without explicitly doing such a reset. Perhaps i’ll add it back when a problem is encountered. However, it doesn’t sound reasonable to me that you need to do a reset for every gameobject instantiated.

The vast majority of my MonoBehaviours use an initialization function like this, and I serialize all the variables I can there, instead of using Awake. So throwing this stuff in is no big deal for me. Still, I’d love to be able to stop doing this component hiding kind of stuff, just to clean things up slightly, but I won’t unless someone proves to me there’s no longer a benefit. (Unfortunately, not everything serializes, so I have to set up structs, event listeners, etc., in Awake.) I don’t like waiting for games to begin. :x

I see. That’s actually a very good idea to avoid some havoc situations which are difficult to debug. Yep, to get everything cleanly initialized is important. :smile: