- Home /
Health Bar Doesn't Go Down When Colliding With Enemy
I was following a few tutorials and now I have a health bar on top of the screen. The bar goes down when I jump (I wanted to test if it works). And the player dies when the health bar is empty. How can I make it so the health bar goes down when it touches an enemy?
Here is my script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Health : MonoBehaviour
{ public int maxHealth = 100; public int currentHealth;
public HealthBar healthBar;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
TakeDamage(10);
}
if (currentHealth <= 0)
Destroy(gameObject);
}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
}
Answer by SteenPetersen · May 28, 2020 at 09:20 AM
You can use FillAmount in your SetHealth method. So that the fill of the image that represents the health is directly connected to the 'currentHealth' variable. You can follow this tutorial if it is not already this you are following.
Answer by SkaredCreations · May 28, 2020 at 10:17 AM
Add the method OnCollisionEnter (or OnTriggerEnter if your Collider is set as trigger) and call TakeDamage inside it, also you may want to check collision.gameObject.tag inside it to filter only the collisions with enemy gameobjects else you'll take damage also colliding with walls etc.
Also I see that you're checking whether currentHealth reaches 0 inside your Update, that's not necessary since the only line of code where you decreases currentHealth is in TakeDamage so I'd move that statement inside TakeDamage after the call to healthBar.SetHealth
A better approach to your TakeDamage:
void TakeDamage(int damage)
{
// The following line ensures that currentHealth is minimum 0 (avoid negative number)
currentHealth = Mathf.Max(0, currentHealth - damage);
healthBar.SetHealth(currentHealth);
if (currentHealth == 0)
Destroy(gameObject);
}
I'm a beginner in Unity so I'm still learning to write code by myself. Can you tell me what I need to add to this script? The player still only takes damage while jumping. I want him to take damage when hitting an enemy. Script:
private void OnCollisionEnter2D() { TakeDamage(10); }
Thanks for the help :)
Your answer
Follow this Question
Related Questions
2D Collider Isnt working 1 Answer
How to Snap to Grid Cells 0 Answers
2d Animation and Colliders 0 Answers
How to call a function every x frames? 1 Answer
2D Collision Between Two Objects 1 Answer