Static Types Pt.1- C# Skill in Unity: 2

Objective: take a quick peek of static members in Unity.

Static members is a type that would exist in program from beginning till the end. Different with instance type, it would be written in the system of game when Player starts it.
In this tutorial, we would create a quick item class with static variable to count all items across the entire program.

Instance variables

Let’s create a script with Item class in it. Inside class Item, create 2 basic variable of item: name and ID.

Within Start() of ItemManager, create 2 new items.

The variables with Item class are all instance variables now, which means it would not have any reference or value unless they were assigned.
If you do not give “sword” or “shield” a name, it would never be assigned the name.

We can assign the name and ID to both items we created in Start().

Static variable

Now we can add a static variable to class Item.

We will not be able to set the value of this static integer under items we created. In fact, it does not belongs to any items we created, it is in the whole Item class, means every item we created from class Item, there is a “itemCounts” variable in it.

You can not call “itemCounts” under any new item.

To call this static variable in this example, we need a constructor.
Inside this constructor, we would count the numbers of item we create in Start().

And now we can call this static variable in Start() to know how a static member works.
Since the static variable is in the whole class Item, it can be called by class itself.

Then we can run this script in editor to check the result, which should shows “2” as we already create 2 items in Start().

As we created more items in Start(), the static variable would be called and calculate the sum of all class Item.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store