Why OnCollisionEnter function not used inside Update function?

I know this is a very elementary question but I think it’s an important one to understand. If OnCollisionEnter is a function that deals with different “interacting” objects, then why is it not nested or even called in the Update function? Does the OnCollisionEnter function check frame by frame just like anything inside the Update function? Is this one of those “magical” Unity functions like OnGUI? I know that you can’t put one function inside another in that regard, but why not just put some code inside Update that would do the same thing as OnCollisionEnter? Please enlighten!

Sort of. OnCollisionEnter is part of the physics engine, which will be called on physics steps. The physics engine runs on a fixed time step, so it has a constant “frame rate”. It isn’t called every frame, but on physics steps when collision conditions are met.

Yes, this method will be called by the engine if the conditions for it are met. You can call it yourself if you want, but it will be called automatically. The physics engine will check every physics step if something is colliding with the object the script is attached to and then call this method with the collision information if a collision occurs. The method will not be called if no collision occurs.

There’s a lot of information on using the physics engine out there, I keep this page in my bookmarks for reference: https://docs.unity3d.com/Manual/CollidersOverview.html

2 Likes

Look at OnCollisionEnter like on an event, when it happens - it fires. Why would you bother checking it all the time, when the engine will inform you when it happens and then you do whatever you have to

You can can call Update, FixedUpdate, OnBlah, every unity callback is also a function and you can call it as wanted when ever, unity just has events to call them for you when X happens(a new frame for update, a physics tick for FixedUpdate, collisions, etc.)

1 Like

What a silly question. You simply can’t know what people have in their minds for their games. An example: You may want to increment a variable to fill a bar while the player is interacting with something.

1 Like

You can use OnCollisionStay in order to check every frame.

3 Likes