Search code examples
c#unity-game-engine

About Instance methods in c# and unity


When I code in general C# and create instance methods, to call them from the same class I have to instantiate the class first and then use the method. But when using Unity, the instance methods I create can be directly accessed in the same class (without instantiating the class).

Why is that?


Solution

  • Besides what everyone says here about static members as I understand your question it has nothing to do with static but you rather wonder why you nowhere are using new for your own or Unity built-in components.

    Whenever a component is attached to a GameObject => an instance already exists because Unity already created it for you. Further there are certain properties like e.g. transform and gameObject which Unity already populates as well for you while attaching that component to a GameObject.

    And of course an instance of your custom component itself can access all of its instance members.