We were profiling (deep profile) our game to check about cpu and garbage generation when we found out that GetComponent() was generating garbage in some cases. After making some tests we discovered that it was when the component is not found and GetComponent() returns null.
We created a test project to replicate this bug in order to easily share it with you.
The project consists of two scenes:
- GarbageTestCaseScene - it has a GameObject with a component/behaviour calling GetComponent() multiple times per update while the asked component is missing.
- NoGarbageTestCaseScene - it has the same component/behaviour but it asks for a component that exists on that GameObject.
To replicate the bug run the first scene and start profiling and you will see that a lot of garbage per frame is generated while on the other scene this doesn’t happen.
This is the code of our behaviour calling GetComponent():
public class GetComponentBehaviour : MonoBehaviour
{
void Update()
{
for (int i = 0; i < 5000; i++) {
AnotherBehaviour component = this.GetComponent<AnotherBehaviour>();
}
}
}
The question is, should this be happening? Why? We know it is not recommended to call GetComponent multiple times per update but we need it in some cases and we are willing to pay the CPU cost but not the garbage generation one.
The test cases were tested using Unity 4.3.4f1 pro and 4.3.2f1 free.
UPDATE: in case anyone wants to know, the issue case is 590565.