GetComponents and GetComponentsInChildren and GetComponentsInParent have these overloads available:
public void GetComponentsInParent<T>(bool includeInactive, List<T> results);
public void GetComponentsInChildren<T>(bool includeInactive, List<T> result);
public void GetComponents<T>(List<T> results);
//also this one, for when you hate writing good code:
public void GetComponents(Type type, List<Component> results);
Doing a quick check, it seems like the methods clear the provided list, and then put the results in it. It seems like this is meant as a gc-free alternative to GetComponents (yay!). Using a List instead of an array with an int return that defines the count of elements also makes this a much better solution to the gc problem than eg. Physics.RaycastAll and NavMeshPath.GetCornersNonAlloc!
It’d be nice to have clear docs on what the method does, though!
The Component version of the docs does not have it.
The GameObject version does.
But it does not say the list is cleared. Which seems a waste. Not sure why i would want to use the list version if its cleared. If i want to collect a bunch of components into a single list i still have to append them to another list.
I would expected i would of been able to do this.
goA.GetComponentsInChildren(true, _TmpRenderers);
goB.GetComponentsInChildren(true, _TmpRenderers);
@daxiongmao Funny you mention that – I needed to accumulate a bunch of components like that – so having it NOT be cleared (and mentioning this in the docs) would be super helpful for our sanity and the computer’s performance.
It get’s cleared (which I do not like). Would be nice if the list will not be cleared.We overcome that with 2 internal lists now, however, this is a bit hacky!
I mean, that’s roughly the rate the docs get fixes. It would probably go faster if instead of actual docs all we wanted was silly sports car analogies.
hello! wow this is a bit overdue isn’t it This landed on my desk in January, and I’m pleased to say the docs have now been updated. I ended up updating the docs on the whole “GetComponent” family (both on the Component and GameObject class) which includes:
They now all prioritize the generic versions at the top, with the older and less efficient typeof & string overloads listed afterwards. It now explains how the versions work where you pass in a List for the results (as requested by Baste in 2016!) The code samples remain similar but with a few improvements and corrections, and in general all the pages are more consistent with each other, and mention the relevant alternatives where appropriate.