Classes get instantiated automatically ?

Hello !

I am new to unity but not to object oriented languages. I have made some c# scripts and attached them to my player and I think that once the game starts it automatically creates an instance of each class in the scripts.

I find this a bit confusing as normally in any object oriented languages you have to instantiate the classes yourself, and does this mean that I cannot create instances of the classes of my scripts ?

Also when you want to extend or implement a class from other script, do you have to add that script to the character too ? I ask this because then if unity instantiates automatically the parent script it would be a waste of memory.

I just find all this rather confusing and I did not find anything about this in the scripting docs.

1 Like

The short version is:

  • Yes, Unity creates the instances for you. You don’t new() objects.
  • If you want to create a new instance, use AddComponent<
  • Inheritance works as you’d expect. If Cow inherits from Animal, and you want your gameobject to be a Cow, you put Cow on it, and now it’s both a Cow and an animal. No need to attach the Animal script.

Longer:
If you want to attach a script to an object, you have to inherit from MonoBehaviour. In that case, Unity takes care of instantiating the object for you.
MonoBehaviours are dependent on being attached to a GameObject. This means that you can’t create new ones yourself (if you do new Foo(), and Foo is a MonoBehaviour, Unity throws an error at you). If you want to create an instance of the object, you use gameObject.AddComponent(), which creates an instance of Foo and adds it to the gameobject.
Because of this, MonoBehaviours shouldn’t have constructors! Unity doesn’t know which arguments to provide, and there are other subtle reasons. You generally do initialization of the object in Awake.

You can of course use “normal” classes as much as you want! You create them as you’re used to and nothing’s different. But you can’t attach those classes to GameObjects. Just don’t inherit from MonoBehaviour.

Longest:
Serialization is at the center of this. Read this blog post for the details.

4 Likes

Thanks ! Now it is much clearer. Also thanks for the “longest” link I will read it right now.

1 Like

Was looking for this answer for a longgg time and finaly come across it. thanks.

So glad you asked this question damn i cudnt get my head around it. and no body seemed to understand what i was saying but now all clear. Phew! Lol