Skip to content

Instantly share code, notes, and snippets.

@ratkingsminion
Last active November 23, 2022 17:29
Show Gist options
  • Save ratkingsminion/d867cb556ec0f03ccacc2674c6b6c276 to your computer and use it in GitHub Desktop.
Save ratkingsminion/d867cb556ec0f03ccacc2674c6b6c276 to your computer and use it in GitHub Desktop.
C# - An attribute that lets you reset static variables if needed
using System;
using System.Reflection;
using System.Collections.Generic;
// Usage:
// [ResetStatics(nameof(BooleanField))]
// public class MyClass : MonoBehaviour {
// public static bool BooleanField;
// // ...
// }
// In your main class:
// ResetStaticsAttribute.ResetAll();
[AttributeUsage(AttributeTargets.Class)]
public class ResetStaticsAttribute : Attribute {
public readonly List<string> statics;
public ResetStaticsAttribute(params string[] statics) {
this.statics = new(statics);
}
public static void ResetAll() {
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Type type in assembly.GetTypes()) {
var attrib = type.GetCustomAttribute(typeof(ResetStaticsAttribute), false);
if (attrib != null && attrib is ResetStaticsAttribute ror && ror.statics.Count > 0) {
foreach (var s in ror.statics) {
var field = type.GetField(s, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (field != null) { field.SetValue(null, null); }
var property = type.GetProperty(s, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
if (property != null) { property.SetValue(null, null); }
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment