Different types of variables?

Hey all,

I’m trying to understand a script right now and I was just wondering what the difference between a private var and just a regular var, and also I believe I’ve seen global and public vars as well?

So what I was wondering is, what are the different kinds of variables and what do they each do?

Private variables do not show up in your inspector window and static/global variables can be accessed by other scripts.
There are plenty of pages that explain each variable in detail though(LoONuhtiK has given an example).

LoONuhtiK's link is a good place to start.

When I read that page, however, I worry that it could lead to some confusion about what a global variable is and how the static keyword works.

In all likelihood, you do not want to use what that link calls a global variable. (I would personally use the term static variable).

When you create a static variable, it means that there will only be one instance of that variable for the class.

Here's an example that might help explain what static means:

Say you have a class called Tree that represents a tree. You would give it some member variables like height, color, age, etc... These would all be normal, member variables. Every tree you create will have its own height, color, etc...

An example of a static varaiable would be if you wanted to keep track of how many instances of trees exist in the world. You would only want one instance of this variable and it would be associated with the tree class and not any individual tree.

You would define this class like this:

class Tree
    var height : float;
    var age    : int;

    static var totalTreeCount : int;

    function Tree ( h : float, a : int )
        height = h;
        age = a;

        /* increment the tree count */

        totalTreeCount ++;

function testTree () : void
    var funkyTree : Tree = new Tree(40.8, 18);

    Debug.Log("total trees: " + Tree.totalTreeCount);

I think that's how the syntax works... I haven't actually ever used any of that.



I worry that people coming from javascript might expect global to mean you can access the variable from anywhere within your script.

That is actually the default behaviour of all your member variables!

If your script is a MonoBehaviour (something you'll add to GameObjects) just look at it as a giant class. All the variables you declare at the top can be referenced from anywhere in the script.

If they are public, other scripts can reference them directly with dot notation. If they are private, they can only be accessed from within your script.

Public/private also determines whether or not they will be visible in the Inspector.

I hope some of this blathering helps...