Skip to content

Instantly share code, notes, and snippets.

@lynxelia
Created February 10, 2018 02:24
Show Gist options
  • Save lynxelia/c6f9d739f5894541242fce077b6a5c7e to your computer and use it in GitHub Desktop.
Save lynxelia/c6f9d739f5894541242fce077b6a5c7e to your computer and use it in GitHub Desktop.
A replacement base class to use instead of MonoBehaviour. Inheriting from this class will ensure all fields in your class will be garbage collected
public class BaseMonoBehaviour : MonoBehaviour
{
void OnDestroy()
{
foreach (FieldInfo field in GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
Type fieldType = field.FieldType;
if (typeof(IList).IsAssignableFrom(fieldType))
{
IList list = field.GetValue(this) as IList;
if (list != null)
{
list.Clear();
}
}
if (typeof(IDictionary).IsAssignableFrom(fieldType))
{
IDictionary dictionary = field.GetValue(this) as IDictionary;
if (dictionary != null)
{
dictionary.Clear();
}
}
if (!fieldType.IsPrimitive)
{
field.SetValue(this, null);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment