- Home /
Having a problem with damage over time on unity 2d
So i wanna make some kind o fire rain, and if it collides with the player, damage over time is applied, but i want it to happen only when the player isnt receiving damage from the previous hit (from the fire rain), in other words, i don't want the the damage over time stackable.
using UnityEngine; using System.Collections;
public class fire : MonoBehaviour {
public int damageToGive = 3;
public int x=0;
public int playerhurt = 0 ;
// Use this for initialization
void Update ()
{
}
void Start ()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player" && playerhurt==0)
{
InvokeRepeating ("dmgOverTime", 0f, 2f);
}
}
// Update is called once per frame
void dmgOverTime ()
{
if (x < 3)
{
playerhurt = 1;
GameObject player = GameObject.FindGameObjectWithTag ("Player");
HealthManager HM = player.GetComponent<HealthManager> ();
HM.giveDamage (damageToGive);
x++;
}
else
{
playerhurt = 0;
CancelInvoke ();
x = 0;
}
}
}
For some reason, when the playerhurt is set to 1, it gets automaticly to 0, i think it's thanks to public int playerhurt = 0 ; but i can't find a way around, what should i do?
Are you modifying the value of playerhurt in other scripts?
Because the code you've shown here looks fine to me.
@allenallenalle No, what i think its happening is public int playerhurt = 0 ; is always repeating. When i use print(playerhurt); the value "0" appears like 60 times per second, so i think the script itself is working like the update() method, or maybe im completly wrong, i dont know.
Nope. That will only set it to zero when the object is instantiated.
i placed print ("playerhurt value: "+playerhurt); inside the OnTriggerEnter2D
Why does the playerhurt shows at 0 200 times? (~3 secs, while the player was on fire) It looks like it gets set back to 0 as soon as it leaves the loop.
Answer by Sopqos · Apr 13, 2017 at 07:49 PM
@FortisVenaliter Thanks!, the problem was that i had another InvokeRepeating for the fire rain, the easy fix was using the playerhurt in the scrip that calls the rain.
Your answer
