Pages

Saturday, December 18, 2010

Unity3d + C#: Referencing object's script variables...

Just something I kept forgetting when scripting with C#...

If a variable is not "public static", then it cannot be reference from other script such as this:
//If we are taking a bool variable called "canAccess" from another script called "Player.cs"...
Player.canAccess = true;

Thus, in order to reference a variable from a script which is not "public static", first, you need to state the script name as the class of the variable, follow by the name of the variable:
Player playerScript = 

Then, after the equal sign, "cast the variable", before stating the "GetComponent" function:
//"obj" is the game object which you want to access to...
Player playerScript = (Player)obj.gameObject.GetComponent("Player");
//Now you can reference the variable...
playerScript.canAccess = true;

It's kinda long, and I always forgot about the "casting" part...

No comments: