I want to have a list of TrailRenderer that keeps track of all the trail renderers so that I can do operations on all of them without using “FindObjectsOfType” (because I heard Find is slow). My question is: How do I get notified when a new trail Renderer is instantiated or is destroyed so that I know when to add or remove from the list? Is there a call-back function like “TrailRenderer.OnNewTrailRendererInstantiate?”
To clarify, you probably want something along these lines
//In your script that tracks all the trail renderers
public class TrailRendererManager : Monobehavior {
public static List<TrailRenderer> trailList;
void Awake() {
trailList = new List<TrailRenderer>();
}
}
//Attached to every object with a trail renderer
public class TrailRendererInstance : Monobehavior {
void Start(){
TrailRendererManager.trailList.Add(GetComponent<TrailRenderer>());
}
}
Currently on my game I’m using something along these lines. This takes care of the Add / Remove. If you want to be more specific, you can use OnDestroy
instead of OnDisable
public class TrailRenderer : MonoBehaviour {
private static List<TrailRenderer> _TrailRendererList = new List<TrailRenderer>();
public static List<TrailRenderer> TrailRendererList {
get {
return _TrailRendererList;
}
}
void OnEnable() {
_TrailRendererList.Add(this);
}
void OnDisable() {
_TrailRendererList.Remove(this);
}
}
void Awake()
{
var trails = FindObjectsOfType();
}
trails would be an array with all the trailrenderers