Game Development Reference
In-Depth Information
Static is Omnipresent
The static keyword was considered in Chapter 4, when creating Singleton objects. In short, using the
static keyword, you can add variables that completely cut across instance scope boundaries—that
is, variables that retain their value not for a specific instance of a class, but for all instances. If you
need to create a value that applies to all instances of a class, as though it were a shared variable,
then static variables can come in handy (see Listing 10-21 for use of a static variable in a class).
Listing 10-21. Using Static Variables
using UnityEngine;
using System.Collections;
public class MyClass
{
//Variable will be shared for all instances
static public int MyVar = 50;
//Variable will differ among instances
public string Name = "";
//prints static variable to console
public void PrintMyVar()
{
Debug.Log (MyVar);
}
}
public class Sample : MonoBehaviour
{
void Start()
{
//Delcare instances of MyClass
MyClass C1 = new MyClass();
MyClass C2 = new MyClass();
//Static variable set to 100
MyClass.MyVar = 100;
//Both classes will print 100 because they share the variable
C1.PrintMyVar();
C2.PrintMyVar();
}
}
Note Take care with memory management when using static objects. Unity will not automatically clean or
delete static references, even between scene switches.
 
 
Search WWH ::




Custom Search