I’m guessing you mean static vs public variables, because classes can be static or public too. But difference between the variables are that static variables are shared between all instances of same class and public aren’t. So let’s say you have a class “Example” and it has a static variable “varA”.
Example e1 = new Example();
Example e2 = new Example();
in this example
e1.varA
and
e2.varA
refers to same thing. If you change varA in one instance the other will be changed too.
No, that’s not the main problem with static variables. The problem is, they are global variables. Which is fine if you need global variables and have only one instance of the script that declares them, otherwise you are asking for trouble.
Here is an example. Create the following script, save it, add it to two different game objects (preferably two objects with different names), and in the inspector assign the first object’s number var to 1, the other to 2.
var number : int;
static var globalNumber : int;
function Awake(){
globalNumber = number;
}
function Update(){
Debug.Log(this.name + ": " + globalNumber);
}
When you run the code and view the results in the console, you’ll see something like:
Cube1: 1
Cube2: 1
This is because globalNumber was declared static, and all objects that use that script share that variable. If you attempt to assign that variable for one object, it will change the variable for all objects that use that script.
There are no performance implications for you to consider when using static vs instance level variables. It is purely your program architecture that drives which kind of variables to use.
The solution is to not use static variables unless it makes sense to do so.
If you have a score variable in a master script that there is one instance of, it makes sense to declare it static for ease of access from other scripts:
Master.score += 50;
Otherwise, use public variables. If you need one script to communicate with another, use BroadcastMessage() or GameObject.Find() along with GetComponent(). More info below.