- Home /
[SOLVED]Problem with 2D Collider
Hey, everyone!
I'm making a health system for the player, and I'm having a few troubles with colliders. The problem is, when the player hits the enemy, it triggers the OnTriggerEnter() function two to three times, therefore causing the player to take damage multiple times when you hit the enemy once.
Here is the player script. (You don't need to see the enemy script because the player script handles the damage for the player, not the enemy script):
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerHealth : MonoBehaviour
{
public int healthSlots;
public int health;
[SpaceAttribute]
public GameObject[] objHealthSlots;
private bool sceneSwitch;
void Start()
{
sceneSwitch = false;
healthSlots = 3;
health = 3;
}
void Update()
{
if(sceneSwitch == false)
{
if(health <= 0)
{
SceneManager.LoadScene("StarterStage");
sceneSwitch = true;
return;
}
}
else if(sceneSwitch == true)
{
return;
}
}
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("hit");
if(other.CompareTag("BasicEnemy"))
{
Debug.Log(health);
health -= 1;
}
if(other.CompareTag("HealthPowerup"))
{
health += 1;
}
}
}
I fixed this issue with a variation of the script:
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerHealthTest : MonoBehaviour
{
public int healthSlots;
public int health;
[SpaceAttribute]
public GameObject[] objHealthSlots;
private bool sceneSwitch;
private bool hitSwitch;
void Start()
{
hitSwitch = true;
sceneSwitch = false;
healthSlots = 3;
health = 3;
}
void Update()
{
if(sceneSwitch == false)
{
if(health <= 0)
{
SceneManager.LoadScene("StarterStage");
sceneSwitch = true;
return;
}
}
else if(sceneSwitch == true)
{
return;
}
}
void OnTriggerStay2D(Collider2D other)
{
if(other.CompareTag("BasicEnemy") && hitSwitch == true)
{
Debug.Log(health);
health -= 1;
hitSwitch = false;
}
if(other.CompareTag("HealthPowerup"))
{
health += 1;
}
}
void OnTriggerExit2D(Collider2D other)
{
if(other.CompareTag("BasicEnemy"))
{
hitSwitch = true;
}
}
}
But the problem with this script is that the player can become invincible by staying within the collider of one of the enemies therefore if another enemy hits the player, the player won't be taking any damage because the player must leave the enemy collider before taking anymore damage.
Here is a screenshot of the enemy colliders(its the same with the player):
And here is a screenshot showing the scale of the player and enemy compared to the screen:
Thankyou in advance.
Why don't you log the name of the collidee? I bet it's just multiple colliders triggering because either the player or the enemy has multiple of them.
Thank you for solving my problem. as you said it was the sheer amount of colliders that were causing the problem; because both of the colliders on the enemy were tagged as "BasicEnemy", the players' script was triggering the damage twice.
Thank you.