Skip to content

Instantly share code, notes, and snippets.

@SixWays
Last active May 13, 2018 15:12
Show Gist options
  • Save SixWays/06304159e7219485322ef01957693500 to your computer and use it in GitHub Desktop.
Save SixWays/06304159e7219485322ef01957693500 to your computer and use it in GitHub Desktop.
using UnityEngine.SceneManagement;
/// <summary>
/// Data wrapper that automatically resets to default value on scene load.
/// Make a static instance for safer per-scene static access to data.
/// </summary>
public class SafeStatic<T> {
public T value;
public T defaultValue;
/// <summary>
/// Create a new SafeStatic instance with a default value of default(T).
/// </summary>
public SafeStatic(){
defaultValue = default(T);
SceneManager.activeSceneChanged += (sOld, sNew)=>{value = defaultValue;};
}
/// <summary>
/// Create a new SafeStatic instance with identical default and initial values.
/// Dangerous for reference types, as defaultValue and value will point to the same object!
/// </summary>
public SafeStatic(T defaultValue) : this() {
this.value = this.defaultValue = defaultValue;
}
/// <summary>
/// Create a new SafeStatic instance with default and initial value.
/// For reference types, defaultValue and value should not point to the same object.
/// </summary>
public SafeStatic(T defaultValue, T value) : this() {
this.value = value;
this.defaultValue = defaultValue;
}
}
// Example
/*
public class MyClass {
// someState will reset to false every time the scene loads
static SafeStatic<bool> someState = new SafeStatic<bool>(false);
public void ToggleForWhateverReason(){
someState.value = !someState.value;
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment