- Home /
How to keep track of all objects of same type?
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?"
Then do that? I dont understand what you are asking you literally typed out that you wanted. So create a collection/ array of TrailRenderers then and when you create a new object with one then add it to the collection.
$$anonymous$$y question was not clear, I updated it :)
Hello, thrre is no callback function at all, but trail renderers are allways attached to momobehaviour and they do have Awake and OnDestroy methods, so one of the most efficients ways of achieving what you need is creating another script that works as a mánager, A$$anonymous$$D one script for each trail obj that adds a reference to the manager when it gets instantiated A$$anonymous$$D removemos the reference when it gets destroyed
Answer by unity_ek98vnTRplGj8Q · Jan 30, 2020 at 03:59 PM
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>());
}
}
This but depending on what you use the trail it should also contain
void OnDestroy()
{
TrailRenderer$$anonymous$$anager.trailList.Remove(GetComponent<TrailRenderer>());
}
otherwise you might have a shitton of nullrefs in that list.
Answer by dan_cmj · Jan 30, 2020 at 05:57 PM
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);
}
}
Answer by xxmariofer · Jan 30, 2020 at 07:42 AM
void Awake()
{
var trails = FindObjectsOfType<TrailRenderer>();
}
trails would be an array with all the trailrenderers