close
Coroutine 運作模式
翻譯作 [ 協程]
與子程序不同地地方也是最大的特點可以中斷並且繼續重中斷點繼續執行
簡單來說就是 A -> B 停止 下次就是從 B 開始繼續執行且不影響主程序
以下程式碼能夠清楚理解 Coroutine 運作模式
說明 :
假設有一個角色有血量,魔力,位置
+HP 100
開始移動X位置 每0.1秒 +10平移量
+HP 100
開始移動Y位置 每0.01秒 +10平移量
+MP 5 * 5次
表現是個子程序外,還能特過中斷後從中斷點繼續 且不會互相影響的效果
using UnityEngine; using System.Collections; public class CoroutinesExample : MonoBehaviour { private Char Char1; void Awake() { Char1 = new Char(); } void Start () { Char1.addHP(100.0f); StartCoroutine(MyCoroutineX(Char1.pos)); Char1.addHP(100.0f); StartCoroutine(MyCoroutineY(Char1.pos)); for(int i = 1; i < 5; i++) { Char1.addMp(5.0f); } } IEnumerator MyCoroutineX (Vector3 Pos) { while(Pos.x < 100) { Debug.Log("Pos.x: " + Pos.x); yield return new WaitForSeconds(0.1f); Pos.x += 10; } } IEnumerator MyCoroutineY (Vector3 Pos) { while(Pos.y < 100) { Debug.Log("Pos.y: " + Pos.y); yield return new WaitForSeconds(0.01f); Pos.y += 10; } } } public class Char{ private float HP; private float MP; private Vector3 Pos; public float hp{ get{ return HP; } } public float mp{ get{ return MP; } } public Vector3 pos{ get{ return Pos;} } public Char() { HP = 100; MP = 100; Pos = Vector3.zero; Debug.Log("Create Char - HP: " + HP + " ,MP: " + MP + " ,Pos.x: " + Pos.x + " ,Pos.y: " + Pos.y); } public float addHP(float f) { HP += f; Debug.Log("HP: " + HP); return HP; } public float addMp(float f) { MP += f; Debug.Log("MP: " + MP); return MP; } }
仔細看清楚,訊息的順序就能明白運作模式
歡迎光臨 ~ Eg 程式筆記的天堂
當你看完此篇文章,如果你覺得文章不錯
可以留下鼓勵的留言~
將是我的撰寫更多相關文章的動力
文章標籤
全站熱搜