Blogger Information
Blog 95
fans 0
comment 11
visits 248806
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
协成方法的使用 Coroutine
龍__遇见彩虹的博客
Original
1265 people have browsed it
using UnityEngine;
using System.Collections;
/*
 *协成方法的使用  Coroutine
 * 
 * 1.返回值是IEnumerator
 * 2.返回参数的时候使用yield return null/0;
 * 3.协成方法的调用 StartCoroutine( method() );
 */ 
public class DemoController : MonoBehaviour {
    private void Start()
    {
        //可以在任意地方调用协成方法
        StartCoroutine(printStr());
    }
    IEnumerator printStr()
    {
        print("1");
        yield return new WaitForSeconds(1);//等待一秒后执行下一步
        print("2");
        yield return new WaitForSeconds(5);//等待五秒后执行下一步
        print("3");
        yield return null;
    }
}


using UnityEngine;
using System.Collections;
/*
 *协成方法的使用  Coroutine
 * 
 * 1.返回值是IEnumerator
 * 2.返回参数的时候使用yield return null/0;
 * 3.协成方法的调用 StartCoroutine( method() );
 */ 
public class DemoController : MonoBehaviour {
    public GameObject tarGet;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(colorChange());
        }
    }
    IEnumerator colorChange()
    {
        //死循环
        for (;;)
        {
            Color tarGetColor = tarGet.GetComponent<MeshRenderer>().material.color;
            
            //Lerp  当T=0返回a,当T=1返回b时,当T=0.5返回a和b的中点时
            Color newColor = Color.Lerp(tarGetColor, Color.red, 0.02f);
            tarGet.GetComponent<MeshRenderer>().material.color = newColor;
            yield return new WaitForSeconds(0.02f);
            if (Mathf.Abs(Color.red.g - newColor.g) <= 0.01f)
            {
                break;
            }
        }
    }
}



**协成方法的启用和停用--停止协成StopCoroutine

传入返回值:

private IEnumerator ie;
if (Input.GetKeyDown(KeyCode.Space))
{       
    ie = colorChange();
   StartCoroutine(ie);
}
if (Input.GetKeyDown(KeyCode.S))
{     
     StopCoroutine(ie);
 }


使用方法名字符串:

if (Input.GetKeyDown(KeyCode.Space))
{
   StartCoroutine("colorChange");
}
if (Input.GetKeyDown(KeyCode.S))
{
   StopCoroutine("colorChange");
}


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post