}
using UnityEngine; using System.Collections; public class Receive : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void DisplayInfo(){ print (this.gameObject.name+" : Receive diao yong"); } public void DisplayInfo(int n){ print ("Receive diao yong n:"+n); } }
using UnityEngine; using System.Collections; public class CoroutingTest : MonoBehaviour { //协程是指开启一段程序,协同当前程序的执行,不是多线程 // Use this for initialization void Start () { print ("1"); //StartCoroutine ("CoroutingDemo1");
StartCoroutine (CoroutingDemo1());//这种调用方式好一点,当方法含有参数时可以直接在括号里写参数 print ("5"); } // Update is called once per frame void Update () { } IEnumerator CoroutingDemo1(){ print ("2"); yield return new WaitForSeconds (5f); print ("3"); yield return new WaitForSeconds (2f); print ("4"); } void OnDisable(){//当此脚本的enalbe=false时调用此脚本 //topCoroutine ("CoroutingDemo1");//关闭单个开启的协程 StopAllCoroutines ();//关闭所有的协程 } }
using UnityEngine; using System.Collections; public class Cotouting : MonoBehaviour { public Vector3 targetPosition; public float moveSpeed; // Use this for initialization void Start () { //StartCoroutine (CountDown("Messgae")); //StartCoroutine (SaySomeThings()); //StartCoroutine (RepeatMessage(5,1f,"nihao")); StartCoroutine (MoveToPosition(targetPosition)); } // Update is called once per frame void Update () { } IEnumerator CountDown(string msg){ for (float i = 3; i >=0; i-=Time.deltaTime) { yield return 0; } print (msg); } IEnumerator SaySomeThings(){ print ("started"); //yield return StartCoroutine (Wait(1f)); yield return new WaitForSeconds (1f); print ("1s"); yield return StartCoroutine (Wait(2.5f)); print ("2.5s"); } IEnumerator Wait(float duration){ for (float i = 0; i <= duration; i+=Time.deltaTime) { yield return 0; } } IEnumerator RepeatMessage(int count ,float frequence,string msg){ for (int i = 0; i < count; i++) { print (msg); for (float j = 0; j <=frequence; j+=Time.deltaTime) { yield return 0; } } } IEnumerator MoveToPosition(Vector3 target){ while(transform.position!=target){ transform.position = Vector3.MoveTowards (transform.position,target,moveSpeed*Time.deltaTime); yield return 0; } } }
