- Home /
Global Variables
I have a question regading global variables.
Am I allowed to define a
GlobalVariable inside of my GameSystem class? Such like in the "Player Class"
He has a inventory. Can I make this inventory:
public static Ilist name = new IList();
Making this static will allow me to access this inventory bag from any other script correct?
Answer by boymeetsrobot · Oct 24, 2010 at 08:44 AM
You are on the right track with the static variable. Just remember that a static var is a class based var as oppose to an instance of the class. Because of this you would access it via the class name instead of the instance name:-
public class GameManager : MonoBehaviour {
public static float myStaticFloat;
And in your class that wishes to access it you would do:-
GameManager.myStaticFloat = 1.5f;
Answer by _Petroz · Oct 23, 2010 at 11:11 PM
Given you asked a another question regarding architecture, I will offer an alternative approach because generally global variables are a sign of bad architecture. Reducing the scope of variables reduces the complexity of code.
You could make the inventory internal to the Player and make it public, or better yet private and accessed via property. Any object which needs to access the player inventory should have access to the player.
If they don't you could always take the quick way out and use GameObject.Find, although that relies on global state, it's an improvement over introducing additional global state to your game.
Answer by Bravini · Oct 23, 2010 at 06:29 PM
exactly, you will reference it through scriptname.name(); as a good practice, I recommend you define static vars with all capped name ie: MYSTATICVAR so it's easy to see wether it's global or local.
When you say reference it through scriptname.name().
I don't quite undersatnd what you mean. Do I setup a method/function to return the variable? Then in my other script I do a method call to return the object to the other script?
Also since name is a list. I don't quite understand scriptnam.name()?
Name is not a method/function? Am I missing something here? Or is this Unity magic with global vars allowing me to do .name()?
when set to static, you can access an attribute directly through the script name, as if it where attached to the object.