1
\$\begingroup\$

This is my first game attempt and I'm trying to create a game where my player (a box) stops whenever it collides with an obstacle. However, the log for the collision is only displayed when the player collides with the original obstacle, while no message is displayed for colliding with any other obstacles. Here's my code:

public class PlayerCollision : MonoBehaviour
{
    public PlayerMovement movement; //Reference to player movement script

    //This function will run when collision occurs, the info collision is stored in collisionInfo
    void OnCollisionEnter(Collision collisionInfo)
    {
        if (collisionInfo.gameObject.name == "Obstacle")
        {
            movement.enabled = false; //Stop the player from moving
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

its obvious that your OnCollisionEnter only works that is collided with other object with name of "Obstacle". when you duplicate an object the name changes like Obstacle(1).

if you want it work, you have to rename new objects as first one. right solution for this problem is tags. tags are shared names for group of objects.

instead of collisionInfo.gameObject.name use collisionInfo.gameObject.tag thenin up right side of you screen find tags section and define new tag named Obstacle and set this tag to all of your obstacles. when you duplicate and object, new one still has same tag.

\$\endgroup\$
  • \$\begingroup\$ Don't forget to use CompareTag() rather than .tag == :) \$\endgroup\$ – DMGregory Aug 29 at 21:37
  • \$\begingroup\$ @DMGregory what? does it really matter? \$\endgroup\$ – virtouso Aug 29 at 21:38
  • 1
    \$\begingroup\$ It does. .tag == can allocate, but CompareTag() does not. Though if we care about efficiency, discriminating object types by layer rather than tag can be even faster. :) \$\endgroup\$ – DMGregory Aug 29 at 21:42
  • \$\begingroup\$ It works, thank you very much.... \$\endgroup\$ – Shashank Saumya Aug 29 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.