Created
February 10, 2018 02:24
-
-
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
This file contains hidden or 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
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