- Home /
Is calling OnCollisionEnter2D on allot of GameObjects bad for performance?
Hi!
I want to make a 2D game for mobile devices using C#. The goal of the game is to shoot objects with a bullet. In my scene I have always only one bullet and around 70 targets.
Is it better for performance to have ONE Gameobject (the bullet) with a script having the function: OnCollisionEnter2D, or is it okay to have around 70 Gameobjects that all have a script with the OnCollisionEnter2D function?
I ask this because if the OnCollisionEnter2D is called every frame like Update (not sure about this), its probably better (for performance) to call the function only on one Gameobject, rather than on 70?
Thanks in Advance!
Note: I'm just starting out with Unity. This is also my first question on the forum. I'm sorry if i ask this in the wrong place or if my question is not clear enough.
Answer by Commoble · Apr 25, 2017 at 05:42 AM
OnCollisionEnter2D is only called in the single frame in which another object begins to touch your object with the script (as opposed to OnCollisionStay2D, which is called for every frame while another object is touching your scripted object).
Furthermore, it doesn't matter if you have one object with the script on it or seventy; collision event functions will only be called on the specific objects that are colliding. Having a lot of physics-enabled objects can impact performance if you have a lot of them, but this performance impact will be the same with or without having OnCollisionEnter2D in those object's scripts.
Thank you for your clear explanation. You're answer helped me allot!
Answer by Arminyazdian · Apr 25, 2017 at 01:17 PM
No. it just called one time when a game object collides with it. But for detecting a collision or a trigger between two objects you are suppose to add a rigid body component to one or the both. this would decrease the performance a bit.