Unity制作倒计时颜色渐变

Unity制作颜色渐变的倒计时

项目需要制作颜色渐变的倒计时,挺简单的代码,大体思路就是开一个协程,在协程里面控制颜色的变化以及进度条的进度,话不多说代码奉上

public void ShowSliderWithId(int time)
{
    GameObject sl = (GameObject)Instantiate (_sliderPrefab);
    sl.transform.parent = transform;  //设置父节点
    sl.transform.localScale = new Vector3 (1f,1f,1f);
    sl.transform.localPosition = new Vector3 (0f,0f,0f);
    sl.GetComponent ().value = 1f;
    StartCoroutine (ScheduleUpdateGlobal (sl,time));
}

IEnumerator ScheduleUpdateGlobal(GameObject obj,int time)
{
    float seconds = 0;//倒计时时间
    UISlider slider  = obj.GetComponent ();
    UISprite sprite = obj.GetComponent ();
    while(true)  
    {  
        for (float timer = 0; timer < 1; timer += Time.deltaTime) {//控制时间1秒走完
            seconds += Time.deltaTime;  
            slider.value = (1-seconds / time);
            if (seconds > time / 2) { //时间到达一半开始我这里要求是时间过去一半颜色开始变化
                float g = ((time - seconds) * 2 / time);
                sprite.color = new Color (1, g, 1, 1);//控制g渐变为红色
            }
            yield return 0; 
        }
        if (seconds >= time) {
            GameObject.Destroy (obj);
            break; //跳出死循环
        }
    }
}

我用的是环形进度条,我的ui用的是NGUI,需要在Inspector面板中UISprite里面的type选择filled,fillDir选择redial360;
Unity制作倒计时颜色渐变_第1张图片

你可能感兴趣的:(Unity-NGUI)