So, I’m making a 2D game, and in the game the player takes damage when the enemy collides with the player, however, when the player collides with the enemy, the players health drops to zero almost instantly. I was wondering how I could fix this. I have tried looking for a solution without asking, and I couldn’t find anything.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class playerHealth : MonoBehaviour
{
public int Health = 100;
public GameObject player;
bool damage;
void OnCollisionEnter2D(Collision2D Col)
{
if (Col.gameObject.tag == "Enemy")
{
damage = true;
}
}
void OnCollisionExit2D(Collision2D Col)
{
if (Col.gameObject.tag == "Enemy")
{
damage = false;
}
}
void Update()
{
if (Health <= 0)
{
Debug.Log("Died");
//Destroy(player);
//Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name);
}
if (damage)
{
StartCoroutine(takeDamage());
}
}
IEnumerator takeDamage()
{
while (damage)
{
Health -= 5;
yield return new WaitForSeconds(5);
}
}
}
If someone could help, that’d be really appreciated. Thanks.