Hi, basically I’m making 2d shooter, I have a pickup object which makes player bullets explode after hitting something. Bullets use collider and OnCollisionEnter2D to detect collision, the codes are basically like:
and all the obstacles and walls are made of blocks, so it is very likely for a bullet to hit several blocks at the same time when shooting at the corner, I’m well aware of that, my initial expectation is the bullet should only explode once even though there could be a few collision registrations, since the bullet destroy itself after the first OnCollisionEnter2D Call.
But it looks like that’s not the case, if I shoot at the corner there could be up to 3 explosions being instantiated, I also tried DestroyImmediate(), same problem. So my question would be how to avoid that?
Use a bool to ensure it only runs once. Destroy only marks an object for deletion, the actual deletion doesn’t happen until the end of the frame it is called in and the physics loop could run twice in that frame. Add a bool and return if it is true.
Problem is, I also have an item which gives player projectiles the ability to ricochet, the ricochet bullet combined with explosive bullet could make a bullet explode multiple times, I would like to preserve this synergy, basically, what I really want is not a bullet should only explode once, but explode only once when hitting multiple objects at the same time.
maybe adding a timer to prevent successive explosions within a really tiny period could help?
or Just use SphereCast or something to detect collisions, but I’m not sure putting collision detecting codes in Update is a good way or not