Declaring Static Types

Natalia DaLomba
Women in Technology
3 min readAug 18, 2023

Static types use the keyword static. You can make classes, variables and even methods static. Static information can be thought of “stuck” in your program’s memory in the life of the program.

There is just 1 of any static type you declare in the universe! It’s only created once, when your C# class is loaded on startup of your program, or C# Domain Reload in Unity (aka when Unity finishes compiling your scripts and loads all your C# code to start running it). Static types are initialized then, if you write an equal sign (=) after it.

In this example, we want this AddToScore class to receive input. We’re going to create a program where we can add 10 points to a score variable. We will accomplish this initially without the use of static types.

Now let’s create another class that is going to keep track of our score. Create a game object in Unity and attach a new script called ScoreTracker to the game object.

Go back to the AddToScore script and get a reference to ScoreTracker by dragging it in the inspector.

score is an instanced variable. We had to go through this hoop of getting a reference to it and then being able to access that data.

Let’s change score to be a static variable. Now, this score variable specifically is going to stay for the life of the game. This data is probably never going to be destroyed — and even if we did destroy this object, the data is still there. It exists for the life of the game.

We can make this static like so:

Now, access ScoreTracker at the class level and use the dot operator to access score. You don’t need to create a reference like we had before at the top.

Something to keep in mind is every time you create a new instance of a non-static game object, for example, you’re creating a copy. Where, every time you create a static variable, there’s one original version that is shared across all instances.

Note that this data is now in memory for the life of the game.

So you need to keep that in mind when you’re creating large games. If you’re coming to a point where you’re running into memory issues, perhaps you need to consider: Are you using static information? And if so, do you need to free up that information to be used and reallocated?

You can also make your methods static. Note that static methods are not able to communicate with non-static variables or have non-static variables in them.

You can also make your classes static:

--

--

Natalia DaLomba
Women in Technology

A Unity C# developer inspired by game design logic used to create digital adventures. https://www.starforce.games/devlog/