Not using GetComponent during OnCollisionEnter or OnTriggerEnter
In my project there is a total of about 11,000 rigidbodies. Not all simulate at the same time, but... there can be many OnCollisionEnters in a single frame where I need to a get a reference to a component on the colliding object.
What is a good system to get a reference to the component on the colliding object ,without using GetComponent?
Answer by lgarczyn · Nov 10, 2019 at 12:41 AM
GetComponent is cheap, probably much cheaper than your 11000 rigidbodies moving around.
That said, if you really wanted to avoid it, you could record all of these RigidBodies in a Dictionary, mapping them to the component you are trying to access. Measure performances for both system to check if you actually gained something.
Well like I said they are not actually all simulating at the same time. Only about 200 will simulate at any given time. Which runs smooth on as low as iPhone 7. Its when about 30 collision events happen on a single frame have performance issues. Having just the get component call on collison will drop the frame rate for that frame.
Anyway I will test this to see if has an impact. Thanks.
There are better ways to gain performances with physics:
$$anonymous$$ore info: https://docs.unity3d.com/$$anonymous$$anual/iphone-Optimizing-Physics.html
Additionally, if you use joints, you can reduce the solver count. You can also increase the two friction parameters and sleep threshold to reduce calculations.
Your answer
Follow this Question
Related Questions
How to detect collision of two moving characters? 1 Answer
Collider fires consistently, but Trigger does not? 0 Answers
Recreating 'skin width' functionality on a rigidbody? 0 Answers
How to Ignore Collisions Between a Layer and a LayerMask? 1 Answer
Collision Between Two Child GameObjects 0 Answers