So what does this word “static” do to variables and methods? Well a couple of things.
- static variables and methods that are public are accessible from anywhere without having to first reference or instantiate the class that they are in. Note though that if they are private, they can not.
- They make variables class variables, rather than instance variables. This comes in handy with games especially when you are creating multiple enemies or bullets or obstacles and you want to keep a total count of them. Rather than each instance of the enemy/bullet/obstacle keeping a count, the class as a whole keeps count.
using UnityEngine;
using System.Collections;
public class Obstacle
{
//Static variables are shared across all instances of a class.
public static int obstacleCount = 0;
public Obstacle()
{
}
static public Obstacle SpawnObstacle()
{
//Increment the static variable to know how many
//objects of this class have been created.
obstacleCount++;
GameObject oGO = Instantiate<GameObject>(GameManager.ObstacleSO.GetObstaclePrefab());
Obstacle obst = oGO.GetComponent<Obstacle>();
return obst;
}
}
Now one of the cool things about having a static method is that you can reference them directly and I’ll show you the code for that here.
using UnityEngine;
using System.Collections;
public class GameManager
{
void Start()
{
for (int i = 0; i < 3; i++)
{
Obstacle obst = Obstacle.SpawnObstacle();
Vector3 pos = ScreenBounds.RANDOM_ON_SCREEN_LOC;
obst.transform.position = pos;
}
//You can access a static variable by using the class name
//and the dot operator.
int x = Obstacle.obstacleCount;
}
}