Problem by collision with OnCollisionEnter2D class
Hey, 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. 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: https://www.youtube.com/watch?v=IouGpT0AwjI
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. :)
Answer by xKarToSx · May 20, 2021 at 01:00 PM
I have found the solution.
I forgot to query which object touches the collider. I have now changed this and now it works.
private void OnCollisionEnter2D(Collision2D playerCollision)
{
if (playerCollision.gameObject.tag == "Player")
{
SceneManager.LoadScene(0);
}
}