I’m new to C# and Unity. Trying to understand why if I write a script to tell the gameObject that the script is attached to SetActive(false), I use gameObject.SetActive(false). But if I want to rotate the gameObject that the script is attached to, I don’t need to say “gameObject”, I simply say this.transform.Rotate() or even transform.Rotate().
To put it another way, why does transform seem to be built into all scripts automatically, but SetActive isn’t, I have to reference the gameObject first?
transform and gameObject are properties on anything that derives from Component. MonoBehaviour derives from Component, so you get access to those properties.
So, I wouldn’t say that anything is inconsistent here. If you want to turn off an object, you do gameObject.SetActive(false);. If you want to rotate the object that a component is attached to, you do transform.rotation = whatever;
You can’t just say SetActive(false); because you can’t set a Component to be active/inactive! You can enable/disable a Behaviour (not all components are behaviours!), sure, but that’s a completely different thing.
I think the part you’re mixed up on is that transform isn’t being accessed through gameObject – it’s directly available to any Component.
Also, aside: this is only strictly necessary if you need to distinguish between a field and a local variable, like this:
public class Whatever {
public int foo;
public void ReticulateSplines(int foo) {
this.foo = foo * 2;
}
}
What’s even sillier is that there is no checkbox in the Inspector to control .enabled until you provide a Start() method or some other subtle hints. But it’s there.