Skip to content

Instantly share code, notes, and snippets.

@hasanbayatme
Last active November 17, 2023 09:14
Show Gist options
  • Save hasanbayatme/f3ddf56cf261a6b40efc14ecb9881a98 to your computer and use it in GitHub Desktop.
Save hasanbayatme/f3ddf56cf261a6b40efc14ecb9881a98 to your computer and use it in GitHub Desktop.
A simple C# static class to get and set globally accessible variables through a key-value approach (C#, Unity, .NET)

This is a simple C# static class to get and set globally accessible variables through a key-value approach.

Installation

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.

Usage

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");
  }

}

API

Getting a Variable

Description

Gets the variable by the given key and casts it to the provided type argument T.

Parameters

  • key: The variable name/key.

Returns

Returns the variable value casted to the provided type.

T GlobalVariables.Get<T>(string key);

Setting a Variable

Description

Sets the variable by the given key.

Parameters

  • key: The variable name/key.
  • value: The variable value.
void GlobalVariables.Set(string key, object value);

Getting All Variables

Description

Gets all the variables.

Returns

Returns a dictionary of variables.

Dictionary<string, object> GlobalVariables.GetAll();
using System.Collections.Generic;
/// <summary>
/// A simple static class to get and set globally accessible variables through a key-value approach.
/// </summary>
/// <remarks>
/// <para>Uses a key-value approach (dictionary) for storing and modifying variables.</para>
/// <para>It also uses a lock to ensure consistency between the threads.</para>
/// </remarks>
public static class GlobalVariables
{
private static readonly object lockObject = new object();
private static Dictionary<string, object> variablesDictionary = new Dictionary<string, object>();
/// <summary>
/// The underlying key-value storage (dictionary).
/// </summary>
/// <value>Gets the underlying variables dictionary</value>
public static Dictionary<string, object> VariablesDictionary => variablesDictionary;
/// <summary>
/// Retrieves all global variables.
/// </summary>
/// <returns>The global variables dictionary object.</returns>
public static Dictionary<string, object> GetAll()
{
return variablesDictionary;
}
/// <summary>
/// Gets a variable and casts it to the provided type argument.
/// </summary>
/// <typeparam name="T">The type of the variable</typeparam>
/// <param name="key">The variable key</param>
/// <returns>The casted variable value</returns>
public static T Get<T>(string key)
{
if (variablesDictionary == null || !variablesDictionary.ContainsKey(key))
{
return default(T);
}
return (T)variablesDictionary[key];
}
/// <summary>
/// Sets the variable, the existing value gets overridden.
/// </summary>
/// <remarks>It uses a lock under the hood to ensure consistensy between threads</remarks>
/// <param name="key">The variable name/key</param>
/// <param name="value">The variable value</param>
public static void Set(string key, object value)
{
lock (lockObject)
{
if (variablesDictionary == null)
{
variablesDictionary = new Dictionary<string, object>();
}
variablesDictionary[key] = value;
}
}
}
@Fenikkel
Copy link

Really nice! Thank you!

@otzelpov
Copy link

Great Job, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment