How do you make a global variable, global in Unity?

public float PathLength = 0f;
PathLength = PathLength + SegmentLength;

This gives me the correct data I want, displayed in the Inspector.
I want it displayed in the HUD.
So In My HUDScript I wrote this:

	mytext.text = "Line Length: " + PathLength;

I get this error:

error CS0103: The name `PathLength’ does not exist in the current context

When I want a really global variable what I do is to make a static class to store this variables, like this:

public static class GlobalVariables{
     public static float pathLength; 

This way every single script in my game could access this variable just writing:

GlobalVariables.pathLength = 1.0f;

GlobalVariables.pathLength += SegmentLength;

Or whatever.


public var GiveMePathLengthGO: GameObject; // Drag the GO here which has the script attached to it which has the pathLength variable Initialized.

function Start()

function Update()
 // You can now use the pathLength like so,
mytext.text = "Line Length: "+GiveMePathLengthGO.GetComponent(PathLengthScript).pathLength ; 

Note : PathLengthScript is the script name where you have path length being initialized or wherever you would like to call it from.
This is a workaround , the most ideal way to use is Static class as raulrsd mentioned.

You actually should use a singleton if you really need a global.

Toolbox is a slightly improved singleton for unity you can just grab the code for the classes and add, then make your global in toolbox cs. It’s just as easy, you can call Toolbox.Instance.Myglobals from anywhere. But it is a much better practice if you “need” a global or two.

While there is great debate as to not use singletons at all or not I think they all agree the old static poor practice. I still find singletons useful so I am of the lazy side of the argument I suppose.