Search code examples
c#unity-game-enginecollision-detectioncollisionscene-manager

Unity 3D Collision on gameobject not working


I've made a code where once you collide on a gameobject, it will go to a different scene, the gameobject is a bed, I've applied a tag named Bed, I've applied a rigidbody, I've applied the code to the player where once you collide the code will activate, but for some appearent reason, it still won't work,

here is the code I've applied to the player:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.SceneManagement;

public class PlayerCollision : MonoBehaviour
{
    
  void OnCollisionEnter (Collision Collisionbad)
       {
        
          if (Collisionbad.collider.tag == "Bed")
           { 
                  Debug.Log("Roll Credits");
                  SceneManager.LoadScene("EndingScreen");
           }
        }
}

Solution

  • Your issue is most likely that you are checking the tag of a collider as opposed to a gameObject

    if(Collisionbad.gameObject.tag == "Bed"))
    

    Also, consider using CompareTag as it is more efficient

    if(Collisionbad.gameObject.CompareTag("Bed"))