Trying to damage every 1 second with OnTriggerStay2D()

Hi I’m trying to make a damagezone when hero is inside hero will get 1 damage every 1 second but when hero enters the damage zone first time it gets 2 damage after that it gets 1 how can I fix that

public Material white;
    Material original;
    float time = 0.8f;
    float gettime;
    bool hurt = false;
    void Start()
    {
        original = GetComponentInChildren<SpriteRenderer>().material;
    }

    // Update is called once per frame
    void Update()
    {
        if (hurt) timer();
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {

            if (!hurt)
            {
            
                hurt = true;

                 HealthBar.currentHealth--;


            }
           
        }
    }

   

    void timer()
    {
        if (gettime >= 0)
        {
            gettime -= Time.deltaTime;
            GetComponentInChildren<SpriteRenderer>().material = white;

        }
           
        else
        {
            gettime = time;
            hurt = false;
            GetComponentInChildren<SpriteRenderer>().material = original;

        }


    }

İt works now but ı dont know why here is the code

public Material white;
    Material original;
    float time = 0.8f;
    float gettime=0;
    bool hurt = false;

  
    void Start()
    {
        original = GetComponentInChildren<SpriteRenderer>().material;
    }

    // Update is called once per frame
    void Update()
    {
      
     hitonwhite();
    }


    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {

         if(gettime<0) 
            { 
                HealthBar.currentHealth--;
           

                 gettime = time;



            }

        }
    }

   

    void hitonwhite()
    {
        if (gettime >= 0)
        {
            gettime -= Time.deltaTime;
            GetComponentInChildren<SpriteRenderer>().material = white;

        }
           
        else
        {

            hurt = false;
            GetComponentInChildren<SpriteRenderer>().material = original;

        }


    }

Every frame you are in the Stay() call, increment a float timer, when it reaches 1, reset it and deal the damage.

// code inside of Stay callback:
timer += Time.deltaTime;
// every second, deal some damage
if (timer >= 1)
{
  timer -= 1.0f;
  DealDamage( DamageAmount);
}
1 Like