Stopping the StartCoroutine with blinking function

Posted on

in

,

The solution may seem simple but it took me a while to figure it out so I thought I’d note it here using a blinking function.

  public IEnumerator animateTint(GameObject obj,Color newColour,float speed = 2){
        Color originalColor = newColour;
        Color targetColor = newColour;

        Color defaultBtnColor = new Color();
    ColorUtility.TryParseHtmlString (btnColor, out defaultBtnColor);

    while (obj.GetComponent<Renderer> ().material.color != newColour) {

        Material objMat = obj.GetComponent<Renderer> ().material;
        Color curColour = objMat.color;

        if(closeEnough(curColour.r,targetColor.r) && closeEnough(curColour.g,targetColor.g) && closeEnough(curColour.b,targetColor.b) ){
            //objMat.color = newColour;
            print ("change tint "+targetColor);
            if(targetColor == newColour){
                targetColor = defaultBtnColor;
            }else{
                yield return StartCoroutine(CoroutineUtil.WaitForRealSeconds(1)); //2
                targetColor = newColour;
            }
            //yield break;    
        }

        buttonCode btnCode = obj.transform.parent.GetComponent<buttonCode> ();
    
        if(btnCode.isBlinking){
        objMat.color = Color.Lerp(curColour,targetColor, speed * Time.deltaTime);
        }else{
                objMat.color = Color.white;
            yield return null;
        }
        //print ("tinting "+curColour);

        yield return null;
    }
}

The main part is

yield return null;

Other things going on here are converting a hex code string to a Unity colour using. (btnColor is a variable specified previously).

ColorUtility.TryParseHtmlString (btnColor, out defaultBtnColor);

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031