Search Unity

Damage only once, not keep damaging.

Discussion in 'Scripting' started by Rutenis, Sep 22, 2014.

  1. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Hey, so i receantly ran into this problem. So im adding the damage based on an enemies distance. So Bassically when hes near to me, i add the damage to my character every 0.7 seconds. I want it to loop, so every 0.7 seconds it would damage the player. The problem is that it keeps damaging the player after 0.7 seconds. Whats the problem?

    -Thanks!! :))

    Code:

    Code (csharp):
    1.  
    2. IEnumerator Damaging()
    3.         {
    4.  
    5.            while(ZombieScript.Distance == 0.3f || ZombieScript.Distance < 0.3f)
    6.                 {
    7.                     yield return new WaitForSeconds(0.7f);
    8.                     PlayerHealth -= 1;
    9.                 }
    10.         }
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    For what it's worth, I approach this problem quite differently. Rather than using coroutines, I simply keep track of my last damage time, and don't apply damage again until the time is more than that. Something like the following (crude, untested) pseudocode:
    Code (CSharp):
    1.   public float damagePeriod = 0.7f;
    2.   float lastDamTime = 0f;
    3.  
    4.   void Update() {
    5.     if (Time.time - lastDamTime > damagePeriod && TouchingWhatever()) {
    6.        ApplyDamage();
    7.        lastDamTime = Time.time;
    8.     }
    9.   }
    10.  
    Is easy, no?
     
    Rutenis likes this.
  3. cranky

    cranky

    Joined:
    Jun 11, 2014
    Posts:
    180
    Swap the order of the two lines within your While statement.
     
  4. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Yeah, last time i tried that it didnt work. Now it does. But the problem was that i was adding the damage from another script that i didnt mention. Thanks for the help! :)

    Script that i modified to be like:
    Code (csharp):
    1.  
    2. if(Time.time > NextHit)
    3.         {
    4.             PlayerHealth -= 1;
    5.             NextHit = Time.time + HitRate;
    6.         }
     
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Yep, that's a good way to do it too. Nice job!
     
    Rutenis likes this.