Question about OnCollisionEnter2D method

I found this super confusing. We declare a new method with:

private void OnCollisionEnter2D(Collision2D collision)

but it’s actually an already existing method? Or it has built-in functionality somehow? I’m unclear on how this works.

Also, I would have assumed this would belong in the Update method. Wouldn’t it need to check every frame for a collision?

OnCollisionEnter2D is a method from MonoBehaviour which is a class from which all unity scripts derive.

Technically yes but not exactly look at Order of Execution in the chart during the physics part of it you will see ontrigger and oncollision this is where that is handled so any object which has a collision or trigger on its associated script will executed whatever outcome if any is wanted. More experienced people feel free to correct me if I get anything wrong.

Hey, thanks Willrun! That order of execution page is incredibly helpful, if not partially over my head at this point. But that does help demystify some things a bit.

I’m still confused about the OnCollisionEnter2D method. In the same script, we use the Destroy method like this:

Destroy(gameObject);

But when we use the OnCollisionEnter2D method, we use it like this:

private void OnCollisionEnter2D(Collision2D collision)
    {
    }

So far, this latter syntax has been reserved for creating new methods, but here it’s used with an existing method. Is this just something you have to memorize, or is there a logic to it?

No problem. Happy to help in some small way when you’re stuck or don’t understand something you can ask questions on here just about everyone is helpful, or you can google, check unity answers (although I find people on there to be very rude sometimes), also don’t forget to look through the unity documentation that can be very useful.
Oh and let me just add right now you should just focus on how to use these various built in methods to solve problems, not worry so much about how they do their thing all I can tell you is that some methods have return types, parameters overloads and maybe other requirements I can’t think of right now, think about it they are just tools to get what you want done, done.
For an analogy you don’t need to know how a pen works to use one

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms