unity-game-enginecollision-detectioncollisioncollider

Problem by collision with OnCollisionEnter2D class


I have problem with a simple spike script. I have attached the following script to the spike.

View it works also. The spikes are used in a jump down game. After the player has already jumped down several platforms the script is resolved even if the player does not touch the spikes.

public class CollisionSpikes : MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D other)
    {
        SceneManager.LoadScene(0);
    }
}

Here is a picture of how the spikes and their BoxCollider2D are connected to each other. image

I first suspected when all colliders touched each other that this would lead to this error. But the problem still occurred. Here is a video so you can get an impression of the error: youtube video

Does anyone here have an idea how I can fix this problem? I am relatively new to Unity and C# and unfortunately I am stuck here.

Thanks for your help. :)


Solution

  • Try to place a Debug.Log(other) to find out what is colliding with your spikes. Because you are not filtering it anything that touches it will trigger that code. My advice to you is to filter it. Use some tags.

    Do something like

    void OnCollisionEnter2D(Collision2D other)
    {
        Debug.Log(other); // Find out what is triggering the function
        if(other.gameObject.tag == "player") {
            SceneManager.LoadScene(0);
        }
    }