Static

The keyword static, when applied to a property, variable, method, means that the element belongs to the class itself, and not an object instance of the class. One way to think about this is that a class definition is used to create objects when a program is executing, these objects are dynamic, because they only exist when the code is executing. In contrast, static items belong to the class itself, so they are not associated with dynamic-objects created at runtime.

Example Use:

//class Zombie.cs
public static int numZombies;

//in another class:
int curZombies = Zombie.numZombies;

Static Class

"A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself." MSDN Reference - C# Programming Guide

The Utility class below can be used to provide utility methods to hide and show Canvas groups, since this code will be used quite frequently throughout our project.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public static class Utility  {

    public static void ShowCG( CanvasGroup cg){
        cg.alpha = 1;
        cg.blocksRaycasts = true;
        cg.interactable = true;
    }

    public static void HideCG( CanvasGroup cg){
        cg.alpha = 0;
        cg.blocksRaycasts = false;
        cg.interactable = false;
    }

}

//In another class we can use this by: 
CanvasGroup cg = GameObject.Find ("TxtPanel1").GetComponent<CanvasGroup>();
Utility.HideCG (cg);

Last updated