Bobby Tables
Bobby Tables

Reputation: 3013

Why doesn't the access modifier matter in unity3D

Unity has a set of methods that you can use to implement behavior like Start, Awake, Update this methods have no access modifier which means that they are private in C# classes.

From what I know there's no way in C# to call a private method of another class without using reflection.

public class TestClass : MonoBehaviour {
    private void Start () {
       // How is unity able to call this method if it's private and I'm not calling it anywhere
    }

    void Update () {    
    }
}

So my question is how is unity able to call them if they are private? And why aren't they just protected virtual so you can use override ?

Upvotes: 2

Views: 813

Answers (1)

vmchar
vmchar

Reputation: 1323

Unity itself is written in C++ and uses C# only for user-created scripts. Somewhere in documentation there is mentioned that all this "magic" methods (like Start(), Update() etc are called from C++ side by registering scripts which have this "magic" methods. For this methods it doesn't matter which access modified you use public or protected they will be called anyway.

As for why those methods are not protected virtual I can say that less of this methods you have - the better performance you get. If script doesn't have an Update() method, Unity doesn't have to register this script inside it's scripting system and doesn't have to call it each frame.

MonoBehaviour-derived script have huge overhead in compare of regular C# classes. This is because Unity have to manage all resources (graphics, gameObjects, physics, etc) itself except C# memory (it uses mono garbage collection for this purpose). So it's a good practice to use as less MonoBahaviour-derived classes as possible prefering regular C# classes.

Update: here is a good explanation from comments.

Upvotes: 4

Related Questions