Skip to content

Instantly share code, notes, and snippets.

@simonwittber
Created March 25, 2019 09:04
Show Gist options
  • Save simonwittber/c9db672843ef93be77eb7b7d15d56455 to your computer and use it in GitHub Desktop.
Save simonwittber/c9db672843ef93be77eb7b7d15d56455 to your computer and use it in GitHub Desktop.
Tracks enabled MonoBehaviours.
public class InstanceTracker<T> : MonoBehaviour where T : MonoBehaviour
{
public static List<T> Instances { get; private set; } = new List<T>();
int instanceIndex = 0;
void OnEnable()
{
instanceIndex = Instances.Count;
Instances.Add(this as T);
}
void OnDisable()
{
if (instanceIndex < Instances.Count)
{
var end = Instances.Count - 1;
Instances[instanceIndex] = Instances[end];
Instances.RemoveAt(end);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment