Search Unity

Stopping a player object from flickering when hit

Discussion in 'Scripting' started by serbusfish, Feb 22, 2017.

  1. serbusfish

    serbusfish

    Joined:
    Dec 27, 2016
    Posts:
    247
    I would like my player object to flicker if an enemy hits them. I have achieved this but I cant make the flickering stop. This is what I have:

    Code (csharp):
    1.  
    2. IEnumerator FlashCoroutine()
    3.  
    4.     {
    5.  
    6.         float duration = 2.0f;
    7.         while (duration > 0.0f)
    8.         {
    9.             duration -= Time.deltaTime;
    10.  
    11.             PlayerController.body.active = false;
    12.             yield return new WaitForSeconds(0.1f);
    13.          
    14.             PlayerController.body.active = true;
    15.             yield return new WaitForSeconds(0.1f);
    16.          
    17.         }
    18.         StopCoroutine(FlashCoroutine());
    19.         PlayerController.body.active = true;
    20.  
    21.     }
    22.  
    What did I do wrong? (i'm a newbie so it's probably something simple)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    You don't need to StopCoroutine: when the coroutine ends, it is gone.

    In any case, to use that flavor of StopCoroutine, you have to give it the actual instance of the coroutine that you started with, not the brand-new-made-one that you just created by calling FlashCoroutine() as its argument.

    tl;dr : delete line 18 above
     
  3. serbusfish

    serbusfish

    Joined:
    Dec 27, 2016
    Posts:
    247
    I removed line 18 but it didn't fix the issue, the flickering still won't stop :confused:

    EDIT:

    Correction, the flickering DOES stop, after around 28 seconds! I lowered the 2.0f duration float to 0.2f and now it stops after 2 seconds, but I dont understand why?
     
    Last edited: Feb 22, 2017
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Ah, I see it. You are decrementing one frame worth of delta time each time through.

    But you are only going through that decrementor once every two times 0.1 seconds.

    So if you lop off 0.2 from your duration every frame, it should be just about right.

    Time.deltaTime is only the time since the last Update, not since your coroutine was last running. It is global.
     
  5. serbusfish

    serbusfish

    Joined:
    Dec 27, 2016
    Posts:
    247
    Ah right I see ;) Its all working good now so that's great, cheers for the assistance :)
     
    Kurt-Dekker likes this.