Question by
Sohrab-Hamza · Mar 03, 2018 at 12:18 PM ·
damagehealth
How to make a zombie(enemy) do constant damage when it touches you?
I'm making a zombie game and I can't figure out how to make the zombie damage the player upon contact and have it so that the zombie keeps damaging you until it is not touching or it is dead. I searched the internet and found nothing. Please help. (C# is appreciated)
public class TakeDamage : MonoBehaviour {
public float health = 500f;
public int lol = 0;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("zombie"))
{
health = health - 10;
}
}
}
This script is attached to my fps controller.
Comment
Answer by UltraGearGames · Feb 08, 2019 at 12:31 PM
you should do
private void OnTriggerStay(Collider other) { if(other.gameObject.tag == "zombie") { health = health - 10; } }
Answer by f03n1x · Feb 08, 2019 at 05:44 PM
Similar to what UltraGearGames wrote for the answer but you probably want to make sure the damage isn't done every frame, and maybe instead every/half/quarter second
float damageTime = 1.0f; //How often you want to damage to be done to the player
//change to 0.25f for every quarter second/0.5f for half
float currentDamageTime;
private void OnTriggerStay(Collider other)
{
if(other.tag.equals("zombie"))
{
currentDamageTime += Time.deltaTime;
if(currentDamageTime > damageTime)
{
health -= 10.0f; // this is short hand for health = health - 10.0f; btw
currentDamageTime = 0.0f;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612153840im_/https://answers.unity.com/themes/thub/images/avi.jpg)