包含6節(jié)視頻教程
這個(gè)視頻教程是游戲公司內(nèi)部的員工參與制作的。你可以找到很多熟悉而且流程化的制作技巧。很多技術(shù)是簡(jiǎn)單而且有效的制作模型的方案。仔細(xì)聽老師娓娓道來(lái)。
![]()
|
![]() 本篇文章我們來(lái)看下擴(kuò)展Coroutine:自定義YieldInstruction,Unity 的Coroutine機(jī)制無(wú)疑是這個(gè)引擎的一個(gè)亮點(diǎn),可以把很多異步的邏輯用一種順序的書寫方式去實(shí)現(xiàn),這個(gè)還是很重要的。 關(guān)于Coroutine的原理,說(shuō)實(shí)話,這個(gè)沒有源代碼,不好說(shuō)具體是怎么實(shí)現(xiàn)的?此玫搅薎Enumerator,想象是使用了.Net的枚舉機(jī)制。網(wǎng)上有不是探討Coroutine實(shí)現(xiàn)原理的帖子,有興趣的同學(xué)可以翻開看看。 Coroutine之所以強(qiáng)大,缺不了一系列YieldInstruction的派生類,包括:WaitForSeconds , WaitForFixedUpdate,AsyncOperation等等,我一直在琢磨能不能實(shí)現(xiàn)自己的YieldInstruction派生類呢?今天花時(shí)間嘗試了一些,答案是“不能,也能”,哈哈。為什么說(shuō)“不能”呢,是因?yàn)閅ieldInstruction這個(gè)類可沒什么虛函數(shù)可以去override的,為什么說(shuō)“能”呢!我們可以借用一個(gè)特殊的YieldInstruction派生類,來(lái)實(shí)現(xiàn)等同的功能,這個(gè)類就是Coroutine。 假設(shè)我們想實(shí)現(xiàn)這樣一個(gè)YieldInstruction:當(dāng)一個(gè)動(dòng)畫播放完事兒之后,程序再繼續(xù)。 具體的實(shí)現(xiàn)也很簡(jiǎn)單,首先我們需要一個(gè)IEnumerator的派生類,并實(shí)現(xiàn)其3個(gè)接口,具體代碼如下: using UnityEngine; using System.Collections; public class WaitForEndOfAnim : IEnumerator { AnimationState m_animState; public WaitForEndOfAnim(AnimationState animState) { m_animState = animState; } //-- IEnumerator Interface public object Current { get { return null; } } //-- IEnumerator Interface public bool MoveNext() { return m_animState.enabled; } //-- IEnumerator Interface public void Reset() { } } 這里面核心的邏輯就在“MoveNext”函數(shù)中,我通過(guò)m_animState.enabled來(lái)判斷動(dòng)畫是否播放完了。 有了這個(gè)類時(shí)候,如果我們?cè)趨f(xié)程函數(shù)體中寫:yield return new WaitForEndOfAnim(animState),發(fā)現(xiàn)并沒有其作用。后來(lái)改為:yield return StartCoroutine(new WaitForEndOfAnim(animAttack));就OK了。完整的測(cè)試代碼如下: using UnityEngine; using System.Collections; public class UnitTest : MonoBehaviour { // Use this for initialization void Start() { } void OnGUI() { GUILayout.BeginArea(new Rect(6, 6, 200, 300)); GUILayout.BeginVertical(); GUILayout.Box("Conrountinue測(cè)試"); if (GUILayout.Button("啟動(dòng)")) { StartCoroutine(DoTest()); } GUILayout.EndVertical(); GUILayout.EndArea(); } IEnumerator DoTest() { Animation anim = GetComponentInChildren(); AnimationState animAttack = anim["attack"]; animAttack.speed = 0.1f; AnimationState animHit = anim["hit"]; animHit.speed = 0.1f; AnimationState animDie = anim["die"]; animDie.speed = 0.1f; Debug.Log("1.開始播放攻擊動(dòng)畫。" + Time.time * 1000); anim.Play(animAttack.name); yield return StartCoroutine(new WaitForEndOfAnim(animAttack)); Debug.Log("2.開始播放受擊動(dòng)畫。" + Time.time * 1000); anim.Play(animHit.name); yield return StartCoroutine(new WaitForEndOfAnim(animHit)); Debug.Log("3.開始播放死亡動(dòng)畫。" + Time.time * 1000); anim.Play(animDie.name); yield return StartCoroutine(new WaitForEndOfAnim(animDie)); } } 最后,運(yùn)行結(jié)果看下圖,注意時(shí)間戳: 好了,本篇unity3d教程關(guān)于自定義擴(kuò)展Coroutine的講解到此結(jié)束,下篇我們?cè)贂?huì)。
贊0 踩0 |
未知用戶
2005-2025 朱峰社區(qū) 版權(quán)所有 遼ICP備2021001865號(hào)-1
2005-2025 ZhuFeng Community All Rights Reserved
VIP