So I’ve been optimizing my game for android devices and while using profiler I figured that one of my script taking too much CPU time
C#:
Collider[] m_InPrivateZone = Physics.OverlapSphere(transform.position, m_PrivateZoneRadius);
if (m_InPrivateZone.Length > 0) {
foreach (Collider c in m_InPrivateZone) {
var panzer = c.GetComponentInParent<PanzerController>(); //<--- this line is taking a-lot of CPU time
if (panzer != null && panzer != m_PanzerController) {
if (panzer.isAlive) {
target = panzer;
}
}
}
}
I’m using GetComponentInParent because my panzer’s (tank) base GameObject which have PanzerController component don’t have a collider but it’s child have.
So can anyone suggest me any alternative for GetComponentInParent or just suggest me what can i do to lower the CPU time in this specific code?
First you can simply add a primitive collider to the root object and make it a trigger so it don’t actually collide with anything. Apart from that you should actually place your tanks on a seperate layer so you can use a layermask i your OverlapSphere call.
If you plan to run this code quite often you may want to use Physics.OverlapSphereNonAlloc instead and use a predefined and cached array to avoid the generation of garbage.
Finally if the script you’re looking for is on the root object you can simply use
However unless you have deep nested hierarchies “GetComponentInParent” shouldn’t be too bad. Also keep in mind that if your tank actually has several colliders you would call your code several times for the same tank. So it would actually be better to only put the root on a seperate layer and add a dedicated trigger collider that can be found.