Coding question

In the LoserCollider script, where we call the function OnCollisionEnter2D, it says “void OnCollisionEnter 2D (Collision2D collision)”. I was wondering why do we have to name the argument Collision2D with “collision”? I tried not giving it a name but it threw an error. Thanks for any help.

Hey mechanimal, I think I can get your question answered.

I think it comes in a couple of parts:

  1. We call out the full declaration “void OnCollisionEnter2D (Collision2D collision)” because that’s what the Unity Engine needs in order for us to hook our commands into its collision detection. “void OnCollisionEnter2D (Collision2D collision)” all the language here is required as is, except for ‘collision’. It’s not necessary that the identifier is named ‘collision’, but it must have some name (For instance you could write “void OnCollisionEnter2D (Collision2D collidedObject)”.

  2. As of lesson 72, we have the parameter listed (Collision2D collision) but as of this lesson, we don’t have any use yet for that parameter. I’m guessing that’ll come a little later down the road. So why do we have that argument at all? Well, see number one above-- basically, we include the argument because Unity looks for the exact function with one argument in a game object.

  3. Finally, outside of unity and more to just programming in general. The nature of arguments in a function is to let the language know what to expect by the arguments. So, (Collision2D collision) tells the language two things. First, that you’ll be wanting to use a Collision2D object (and any public functions or public variables it may have) and that your instance of the object is named collision. For example:

    void OnCollisionEnter2D (Collision2D collision) {
    Debug.Log(collision.transform.toString());
    }

Since the Function occurs on our Lose Collider, The ball will be the passed argument (collision). I’m simply printing to the console the collision’s transform component in a string format (Which should print ‘Ball (UnityEngine.Transform)’).

I hope this helps. Good luck out there.

1 Like

Privacy & Terms