'I'm having a problem with the OnCollisionEnter function in C# while making a game in Unity

So I learned that you can use a function called OnCollisionEnter to do different things on gameObjects collisions. I tried something simple :

using UnityEngine;

public class Bouncing : MonoBehaviour
{
    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log("text");
    }
}

I have a player with these children - Camera, Player Body and Ground Check. The Player Body has a capsule collider component (beacuse it's a capsule of course, the collider has the "Is Trigger" option unchecked.). The Bouncer was meant to bounce me about 5 units high (I'll do it sometime, if you have any tutorials or anything that could help me then you can comment it too. :) ) The Bouncer has these components - Rigidbody (it isn't kinematic but uses gravity) and a Box Collider ("Is Trigger" option is unchecked.).

I tried to search help on the Internet, but nothing would work as I would like (beacuse it won't work at all).

Sorry for my bad English, thanks for your help everyone.



Solution 1:[1]

OnCollisionEnter is an event: Unity calls it when the object (which must have a Rigidbody) collides with any collider. This event may occur in both objects, the rigidbody and the hit object. In the player, the code could be like this:

public void OnCollisionEnter(Collision collision)
{
    switch (collision.gameObject.tag) // based on Tag
    {
        case "Ball":
            // do something when hitting ball
            break;
        case "Wall":
            // do something when hitting wall
            break;
    }

    // or based on component
    if (collision.gameObject.GetComponent<Rigidbody>()) 
    {
        // do something when hitting Rigidbody gameobject
    }
    else if (collision.gameObject.GetComponent<Archer>()) 
    {
        // do something when hitting a object with (Archer for exp..) component
    }
}

In the ball, the code is pretty much the same - the only difference is that the col structure contains info about the object hit:

void OnCollisionEnter(Collision col)
{
   if (col.gameObject.tag == "Player") 
   {
     // this rigidbody hit the player
   }
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KiynL