WaitForSeconds in a Coroutine isn't working as I expected

Let’s see if someone can help me.

I have a class whose job is to show messages in a UI Text element. I Would like to show messages informing to the user about the actions he is doing.

The operation is: show message, wait 3 seconds, then hide message. I have this implemented with a coroutine.

The problem comes when I want to show a message at the moment that another one is being shown.
Ideally, the current message should be hidden, and the 3 seconds of the new message should begin.

For some reason that I do not understand, the time that remains for the first message to be hidden is the time that the following message remains visible. That is to say, if the first message has been shown for 2 seconds, the second message is only displayed for one second, the remaining one to reach 3.

There is my code:

public void ShowMessage(string msg, string clr){
		if (isCoroutineRunning) {
			StopCoroutine ("ShowHideMessage");
		}
		StartCoroutine (ShowHideMessage (msg, clr));
	}

IEnumerator ShowHideMessage(string msg, string clr){
	isCoroutineRunning = true;
	textMessageObj.SetActive (true);

	if (clr.Equals("Green")) {
		textMessage.color = Color.green;
	} else if (clr.Equals("Red")){
		textMessage.color = Color.red;
	}

	textMessage.text = msg;
	yield return new WaitForSeconds (3f);
	textMessageObj.SetActive (false);
	isCoroutineRunning = false;
}

I would appreciate any help / advice :smiley:

The reason is simple, StopCoroutine has no effect in your case. When starting a coroutine with the IEnumerator overload, you must call StopCoroutine taking an IEnumerator as parameter too. Otherwise, you stop a coroutine that does not exist because Unity believe the coroutines are different (even if they share the same function name).

private IEnumerator showMessageCoroutine ;

public void ShowMessage(string msg, string clr){
     if (showMessageCoroutine  != null ) {
         StopCoroutine ( showMessageCoroutine  );
     }
     showMessageCoroutine = ShowHideMessage (msg, clr);
     StartCoroutine ( showMessageCoroutine  );
 }
 
 IEnumerator ShowHideMessage(string msg, string clr){
     textMessageObj.SetActive (true);
 
     if (clr.Equals("Green")) {
         textMessage.color = Color.green;
     } else if (clr.Equals("Red")){
         textMessage.color = Color.red;
     }
 
     textMessage.text = msg;
     yield return new WaitForSeconds (3f);
     textMessageObj.SetActive (false);
     showMessageCoroutine = null ;
 }