UnityAPI—Coroutine

public class API08Coroutine : MonoBehaviour {

    public GameObject cube;
    // Use this for initialization
    void Start () {
        //print("hha");
        ////ChangeColor();
        //StartCoroutine(ChangeColor());
        ////協程方法開啓後,會繼續運行下面的代碼,不會等協程方法運行結束才繼續執行
        //print("hahaha");
    }

    private IEnumerator ie;
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //ie = Fade();
            //StartCoroutine(ie);
            StartCoroutine("Fade");
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            //StopCoroutine(ie);
            StopCoroutine("Fade");
        }
    }

    IEnumerator Fade()
    {
        for (; ; )
        {
            //cube.GetComponent<MeshRenderer>().material.color = new Color(i, i, i,i);
            Color color = cube.GetComponent<MeshRenderer>().material.color;
            Color newColor = Color.Lerp(color, Color.red, 0.02f);
            cube.GetComponent<MeshRenderer>().material.color = newColor;
            yield return new WaitForSeconds(0.02f);
            if (Mathf.Abs(Color.red.g - newColor.g) <= 0.01f)
            {
                break;
            }
        }
    }


    //Coroutines
    //1,返回值是IEnumerator
    //2,返回參數的時候使用yield return  null/0;
    //3,協程方法的調用StartCoroutine(method())
    IEnumerator ChangeColor()
    {

        print("hahaColor");
        yield return new WaitForSeconds(3);
        cube.GetComponent<MeshRenderer>().material.color = Color.blue;
        print("hahaColor");
        yield return null;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章