I've learned that a class isn't executed until it's instantiated, so I'm curious how a class can function without me explicitly creating an instance of it. In my case, I'm dealing with a Unity script that inherits from MonoBehaviour. I suspect there's some internal mechanism in MonoBehaviour that takes care of the instantiation automatically, but I'm not completely certain. Just to clarify, my class isn't static or abstract.
3 Answers
Absolutely, MonoBehaviours exist as a component of GameObjects in Unity. They are typically instantiated through methods like GameObject.AddComponent. This is how they integrate into Unity’s event-driven architecture.
That’s a valid point! The documentation can be a bit vague. Essentially, if a class inherits MonoBehaviour and is attached to a GameObject, Unity handles its instantiation.
Just to clarify, classes in C# don't execute on their own. They contain methods that are run under certain conditions. For instance, constructors run when you use 'new', while static methods can be called directly. The entire class isn't executed in a conventional sense until you interact with it in some way.
When you don’t create an instance of a class directly, it usually means you’re working within a framework that manages that for you. Frameworks often have built-in methods to find and instantiate classes, especially if they derive from a base class or implement an interface.

I see that in the Unity docs too, but it’s not clear if that applies only to MonoBehaviour or if it means anything that derives from it will also get instantiated. I find that part a bit confusing, hence my inquiry.