This is a simple C# static class to get and set globally accessible variables through a key-value approach.
Just download the script and import to your project or copy paste it to a script file.
It works in any C# project such as Unity.
It can be a great cross-scene persistent data storage for Unity,
just import the script and use the GlobalVariables
class to set and get data regardless of scenes.
It is also available on UnityCommunity/UnityLibrary repository at Assets/Scripts/Utilities/GlobalVariables.cs.
Take a look at the below usage example to learn how to use the provided API.
In the FirstClass
we set the variables values:
public class FirstClass {
public void SomeMethod() {
GlobalVariables.Set("myStringVariable", "test");
GlobalVariables.Set("myIntVariable", 123);
GlobalVariables.Set("myObjectVariable", new List<string>());
}
}
And then in the SecondClass
we retrieve the values of the variables:
public class SecondClass {
public void AnotherMethod() {
string myStringVariable = GlobalVariables.Get<string>("myStringVariable");
int myIntVariable = GlobalVariables.Get<int>("myIntVariable");
List<string> myObjectVariable = GlobalVariables.Get<List<string>>("myObjectVariable");
}
}
Gets the variable by the given key and casts it to the provided type argument T
.
- key: The variable name/key.
Returns the variable value casted to the provided type.
T GlobalVariables.Get<T>(string key);
Sets the variable by the given key.
- key: The variable name/key.
- value: The variable value.
void GlobalVariables.Set(string key, object value);
Gets all the variables.
Returns a dictionary of variables.
Dictionary<string, object> GlobalVariables.GetAll();
Really nice! Thank you!