- Home /
Player health dropping far to fast
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.
Answer by Natrx · Nov 07, 2021 at 02:45 AM
try changing the collision detection on the rigidbody of the player. I'm not sure which option for the collision detection will work, but just test them all, hopefully that fixes your issue!
Edit: if that doesn't work, you can also try to add a cool down for attacking, or try adding the WaitForSeconds before you are taking damage. And if all that doesn't work, try using a different way of taking damage, without using a while loop. (I'm a beginner at coding so Im not sure what will work)
Thanks, the last thing worked for me, I created a float timer so that I could track how long it has been since the player took damage, and then every time the timer hit 0, I would subtract damage. You're a lifesaver. Thank you!
Your answer
Follow this Question
Related Questions
How to make my health decrease? 1 Answer
I need some help with a Fractional Heart System? 1 Answer
How to Make Health Decrease Over Time 2 Answers