Make your player flash when hit

I’ve been looking at some of the other questions about how to make a character flash when hit but I’ve gotten stuck. Here is the code I have:

	void OnTriggerEnter(Collider other) {

		}
			if (other.tag == "Hazard") {
				curHealth -= 20;
				renderer.material.color = collideColor;
				yield return new WaitForSeconds(.5);
				renderer.material.color = normalColor;
			}

but the code I’m using has a yield which apparently can’t be called here and I’m not sure how to change it.

Your function requires a return value of an IEnumerator in order to yield correctly. Unfortunately, OnTriggerEnter is called expecting a void return value.

        void OnTriggerEnter(Collider other)
        {
           if (other.tag == "Hazard")
           {
             curHealth -= 20;
             StartCoroutine(Flasher); //VERY IMPORTANT!  You 'must' start coroutines with this code.
           }
        }

        // Functions to be used as Coroutines MUST return an IEnumerator
        IEnumerator Flasher() 
        {
            for (int i = 0; i < 5; i++)
            {
             renderer.material.color = collideColor;
             yield return new WaitForSeconds(.1f);
             renderer.material.color = normalColor; 
             yield return new WaitForSeconds(.1f);
            }
         }

The last loop just makes it “flash”, instead of only changing color once.

Try this:

     void OnTriggerEnter(Collider other) {
             if (other.tag == "Hazard") {
                  LoseHealth();
             }
     }

     void LoseHealth() {
         curHealth -= 20;
         renderer.material.color = collideColor;
         yield return new WaitForSeconds(.5);
         renderer.material.color = normalColor;
     }