public void Tank extends MonoBehaviour {
void Update() {
CannonShell shell = GetComponent<CannonShell>();
}
}
Now let’s say I have multiple CannonShells being instantiated. Let’s also assume for some reason I have 1000s of other children on the GameObject Tank is attached to.
My question is how does the GetComponent() method work?
Does Unity store all child scripts as a hashmap of all components? An array? Sorted?
I guess to rephrase my question in CS terms, what is the Big-O complexity of GetComponent()? Would I be better off in this case of maybe grabbing a reference to the Components when they are instantiated, and using those instead of using GetComponent() to grab a reference in the update thread?
As to how they’re stored internally, we have no idea. We do know that they’re managed on the native side of Unity code.
My personal guess is it’s a list, so GetComponent would be an O(n) operation, where n is the number of components added to that particular GameObject. Child GameObjects are only considered in the search when using GetComponentInChildren.
You would be better off caching the Component. Even if Unity does handle them as a hashmap, a direct reference (1 memory operation) is still faster than a hashmap (1 math operation + 1 memory operation).
I suppose it wouldn’t be too hard to empirically determine the complexity: have a GO, add a component and benchmark GetComponent. Then add several hundred more Components and do the same. Add the same amount of Components again and benchmark. Optionally plot the results to a graph. Finally determine the complexity from the benchmarked times.