Last active
May 13, 2018 15:12
-
-
Save SixWays/06304159e7219485322ef01957693500 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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