Blink object on collision

I have a fish where the objective is to avoid Enemy fish. Now when the player fish hits the enemy fish i want the player fish to blink twice (n number if possible)

	void BlinkPlayer(int numBlink)
	{
		for(int i=0; i < numBlink; i++)
		{
			transform.renderer.enabled = false;
			StartCoroutine( Wait (.2f));
			transform.renderer.enabled = true;
			StartCoroutine( Wait (.2f));
		}
	}
	
	IEnumerator Wait(float seconds)
	{
		Debug.Log ("Wait");
		yield return new WaitForSeconds(seconds);	
	}

Then im calling BlinkPlayer() from OnCollisionEnter() Doesn’t matter how lrge value I give for Wait() my player fish doesn’t blink. I also tried taking out the for() loop inside BlinkPlayer(), but that didn’t work out either. Although it does print “Wait” in console.

Any idea what am I doing wrong? I am using unity 4.1 if that matters.

You’re close, but missing one crucial detail.

Unity’s docs say that StartCoroutine returns “immediately”. The function making the call doesn’t wait. It’s only the coroutine itself that waits.

You could probably re-organize it something like this:

void BlinkPlayer(int numBlinks) {
	StartCoroutine(DoBlinks(numBlinks, 0.2f));
}

IEnumerator DoBlinks(int numBlinks, float seconds) {
	for (int i=0; i<numBlinks*2; i++) {
	
		//toggle renderer
		renderer.enabled = !renderer.enabled;
		
		//wait for a bit
		yield return new WaitForSeconds(seconds);
	}
	
	//make sure renderer is enabled when we exit
	renderer.enabled = true;
}

Edit: It occurred to me that it might be easier to control the coroutine by duration (in seconds), as opposed to a fixed number of blinks. Something like this…

public class Blink : MonoBehaviour {
	void Start () {
		StartCoroutine(DoBlinks(3f, 0.2f));
	}
	
	IEnumerator DoBlinks(float duration, float blinkTime) {
		while (duration > 0f) {
				duration -= Time.deltaTime;
	 
	       //toggle renderer
	       renderer.enabled = !renderer.enabled;
	 
	       //wait for a bit
	       yield return new WaitForSeconds(blinkTime);
    	}
 
	    //make sure renderer is enabled when we exit
	    renderer.enabled = true;
	}
}