gameObject.SetActive() compared with transform.Rotate()

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?

Sorry if I’m not making any sense.

Unity’s component architecture

Terminology primer for assets:

1 Like

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;
  }
}
3 Likes

Teeny tiny micro-quibble… Components do not have the .enabled field, that comes in on Behaviours. :slight_smile:

That’s why you cannot disable a Rigidbody; it has no .enabled field because it is a Component: it bypasses the Behaviour side of the family tree.

1 Like

Ah, good point. I remember getting very confused by this at first.

1 Like

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.

Exactly. Why is that? Is it just because it’s just used so much, it just made sense to make it easier to use?

Yeah, I could imagine a world where you have to do it like this:

gameObject.transform.position += Vector3.up;

It’s just more convenient this way. Anything attached an object can directly use the transform for that object.

1 Like