- Home /
I am trying to make a top down shooter. I tried to make it so that when i touched a zombie, i took damage. It doesn't show any errors. Why doesn't it work?
I am trying to make a top down shooter. I tried to make it so that when i touched a zombie, i took damage. It doesn't show any errors. Why doesn't it work?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class damage2 : 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
private void Update()
{
if (Collision2D.Tag.Equals("zombie"))
{
TakeDamage(10);
}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
}
}
Answer by Robotinker · Aug 26, 2021 at 06:17 PM
First, you've defined the TakeDamage function inside your Update function. Move that to before or after the Update() definition. Second, try using the OnCollisionEnter2D or OnTriggerEnter2D methods instead of Update for detecting collisions. That way you have information about the collision itself through the method's Collider/Collision argument.
Your answer
Follow this Question
Related Questions
Health Regen Stop After Damage 1 Answer
Health below zero but shows negative numbers 1 Answer
Need zombie to inflict damage 0 Answers
Health Code, Damage and Healing 0 Answers
Damage trigger? 1 Answer