So you want to keep something around forever (or at least for the life of your game?) well Unity has you covered with Static Types! So what are they exactly? Many things can be static (classes, methods, variables) and when you have one there can only be one like the Highlander. That doesn’t mean that the data is unique just that the variable (or class or method) is and there is only one. More technically that means that the static belongs to the class (as there is only one class) and not the object (there can be many multiples of objects) which can have many member variables.

Let’s look at a practical example of a static variable and member instances.

Here we have a public static int that tracks gold usage. We modified our methods to modify the amount of gold.

Here’s the database that initializes the Items. Here we run the methods attached to each of them items. As you can see below the Items cannot access the static int directly.

Now let’s run the program and see how the amount changes as items are bought and sold.

As you can see the gold amount continues to hold the data despite where it’s being called. Whether you decrement or increment even in another script file (Weapon) it persists for the entirety of the game.

Helper Methods

An excellent use of static classes (and static methods) is Helper Methods. These are methods that (can you guess?) help you do a task. In the example below we have a capsule with a material that we want to change to a specific color when the player press the 1 key. In addition we’ll have it change to a random color when we press the 2 key.

This next script sits on the capsule in question and responds to player input.

This is what the final product should look like. First it switches to blue when the player hits the 1 key. Then if the player hits 2 then it finds a random color.

Static Constructors

The last thing we’ll cover is static constructors. These are used to initialize static members and help you wrap up unmanaged code. Let’s take a look at what that looks like.

When attached to the capsule in the scene it should show this in the console. Showing that static members will be called first before everything when put in a static constructor.

As you can see the three playerstats instances only get called after the static members are initialized this ensures that the single instance only runs once. Static types are incredibly useful shortcuts to making your code easier to maintain cutting down on useless boilerplate. Until next time, happy coding.