Search code examples
unity-game-enginecollision-detection

OnCollisionEnter not detecting collisions (Unity 3D)


I have a problem where everytime I run the unity game the collision detection does not work, I was going to add a fridge to my cooking game that you could open and it would bring up a UI containing all of the items inside the fridge, here is the code for the fridge

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenFridge : MonoBehaviour
{
    public GameObject fridgeUI;
    public GameObject player;
    void OnCollisionEnter(Collision collision)
    {
        Debug.Log(collision.gameObject.name);
        if (collision.gameObject.name == "Capsule")
        {
            fridgeUI.SetActive(true);
        }
    }
}
    

For those that were wondering, I am using a capsule for the player and there is a rigid body on the fridge. If you have anyway to fix this, please leave it in the replies.


Solution

  • Did you check that you're adding your script to the GameObject which has the Rigidbody and Collider attached to? I've just had an issue where it wasn't working for me and it turned that I'd put the script on a parent GameObject and not the GameObject which had the Rigidbody and Collider on it