- Home /
Faster alternative to GetComponentInParent() method?
Greeting guys!
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?
Answer by Bunny83 · Mar 08, 2018 at 05:12 PM
There are several things you can do:
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
c.transform.root.GetComponent<PanzerController>();
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.
Thank you very much! I also ended up using a collider on the root gameObject with trigger turned on and you are right, my tank have 4-5 colliders and this code is running in Update method thats why it taking too much CPU time because of 4-5 calls per PanzerController so better option will be using a collider in root. Cheers!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Understanding Profiler and Optimization ! 0 Answers
Distribute terrain in zones 3 Answers
Save and Load Instantiate Enemies 2 Answers
game does not run correctly from Program Files (x86) folder 0 Answers