Tuesday, April 16, 2019

Unity C#: Static Types

Like with most programming languages, C# has a static keyword that can be used on classes, variables and functions. By using the static keyword, that class, variable or function is available for the lifetime of the game. It's worth noting that if you create a static class, it cannot inherit from the MonoBehaviour class but also that all variables and functions must be static.

Static Members Verses Instance Members

Besides being a member that is available throughout the lifetime of a game, a static member is available to all instances of a class. Instance members on the other hand are different because they are specific to that instance of a class. For example, you have an enemy ship class, that class might have a health member. Generally this type of member would be an instance, as you would want each ship to have a unique amount of health. An example of a static member for an enemy ship class would be a shipCount, which keeps track of how many ships there currently are. With this you don't want each instance of the class to have a unique value for this member, so it would be static.

public class EnemyShip()
{
public EnemyShip()
{
shipCount++;
}
public int health;
public static int shipCount;
}


public class TestClass : MonoBehaviour
{
private void Start()
{
EnemyShip shipOne = new EnemyShip();
shipOne.health = 10;
EnemyShip shipTwo = new EnemyShip();
shipTwo.health = 5;
Debug.Log("Ship Count: " + EnemyShip.shipCount);
}
}

Static Constructor

A static constructor can be used to initialise any static members within a class. This constructor will only be called once unlike the constructors we usually use. It will also be called first before any of the instance constructors.

public class EnemyShip()
{
public EnemyShip()
{
shipCount++;
}
static EnemyShip()
{
shipGroup = "Atlas";
}
public int health;
public static int shipCount;
public static string shipGroup;
}


public class TestClass : MonoBehaviour
{
private void Start()
{
EnemyShip shipOne = new EnemyShip();
shipOne.health = 10;
EnemyShip shipTwo = new EnemyShip();
shipTwo.health = 5;
Debug.Log("Ship Count: " + EnemyShip.shipCount);
}
}

In this example the static constructor is used to set the ship's group to "Atlas", as this is static, all enemy ships will have the same ship group value and is done once before the instance constructors. 

No comments:

Post a Comment