Static keyword

I’m learning c# and Unity for half a year - using online courses like this.

It’s first time I encounter that someone uses “static” keyword so often. I presume that when in class something is static that means that it is shared among all of the instances of this class?

What are pros and cons of using static variables and allocations?

Hi there,
Like you have stated, the static modifier means that the data can be accessed by any instance of the class, and is not specific to a single instance. Or as it says in the documentation:
" Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object."

The positives of this is that you don’t need to create an instance of the class to use a method or variable. In Unity, it also means you don’t need to find a reference to an instance of the object in the scene to use the method.

The downside of this, is that a static method cannot access data that is specific to an instance of the class. You will need to pass this kind of data as parameters into the method instead.

A couple useful examples of how we use static members in this course:

  1. We often use static events in Unity. This let’s all subscribe at a class level to an event, meaning whenever any object of that class type invokes the event we can listen for it. We don’t have to subscribe to it one object at a time. For example, when a player dies, we want to listen for that event. Rather than subscribing to each player as we instantiate them, we can just subscribe to the static OnDie event for the player class. Then when any player dies we can hear this event. Since the event is static, we do not know the specific instance of the player when we subscribed to it. However, using the Action delegate, we pass a specific reference to the object inside the event, so we can access its instance specific data that way.

  2. We also use the static modifier in this course for the Singleton pattern. This allows us to have a reference to to the single instance of a class, without creating a new instance to the class, or without searching the scene for a reference to the class. By saving the reference to the instance of the class as a static member, we can access it at a class level. Any class that can access that class, can now reference the singleton instance and use it’s instance specific data. The downside here, is that we have create a global state for the singleton. Since in in our program any class can access the singleton, it creates a lot of dependency on that singleton. If we were to change the singleton, we might have to make many other changes to the program to adjust to it.

These are both examples in which we use a static member to access data at a class level, rather than an instance/object level. The other way to use static methods, is for helper functions. These are functions that don’t need any object specific data, but can be passed all the data via parameters. For example, let’s say you need a function to calculate the average of 2 numbers. You can have a static function that takes 2 numbers in and returns the average. It would not need any object data to complete this calculation. We often uses methods like this in Unity that are built into Unity’s classes without even realizing they are static. For example, the Vector3.Distance() method is a static method used to find the distance between two points.

Hope this helps, it’s a lot of information. Let me know if you have any questions or if I can clarify anything.

1 Like

Thank for comprehensive reply.
I think I get it. I will copy this post to my OneNotebook for future reference for sure :wink:

One thing that bogs me still.

Singleton in this course are created that way:

    private static HostSingleton instance;

    public static HostSingleton Instance
    {
        get
        {
            if (instance != null) return instance;
            instance = FindObjectOfType<HostSingleton>();
            if (instance == null)
            {
                Debug.LogError("No HostSingleton in the scene!");
                return null;
            }
            return instance;
        }
    }

In another course I was having Singleton was created this way:

public static HostSingleton instance;
void Awake()
{
     instance = this;
}

When you introduced first Singleton in this lecture my eyes turned big. Can you please tell me why do we have to make this “FindObjectOfType” thing, when we can just allocate instance in Awake()?

In the version we do in the course, we have that extra check to ensure that when you try and retrieve the instance, it is not null. If it is null, we use the “FindObjectOfType" to check if it exists somewhere in the scene. Essentially it just a null check method used to retrieve the instance.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms