2017-04-08 48 views
-1
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class Animations : MonoBehaviour 
{ 
    public enum AnimatorStates 
    { 
     WALK, RUN, IDLE 
    } 

    private Animator _anim; 

    void Awake() 
    { 
     _anim = GetComponent<Animator>(); 
    } 

    public void PlayState(AnimatorStates state) 
    { 
     string animName = string.Empty; 
     switch (state) 
     { 
      case AnimatorStates.WALK: 
       animName = "Walk"; 
       break; 
      case AnimatorStates.RUN: 
       animName = "Run"; 
       break; 
     } 
     if (_anim == null) 
      _anim = GetComponent<Animator>(); 

     _anim.Play(animName); 
    } 

    void Update() 
    { 
     if (MyCommands.walkbetweenwaypoints == true) 
     { 
      PlayState(AnimatorStates.RUN); 
     } 
     else 
     { 
      PlayState(AnimatorStates.IDLE); 
     } 
    } 
} 

該代碼工作正常,但我不認爲在更新中多次調用PlayState是正確的。我希望如果它是RUN或IDLE狀態只在Update函數中調用一次。如何在Update函數中只設置一次動畫命令?

一旦walkbetweenpointspoints true或false,它將在Update函數中調用狀態不間斷。

回答

1

保存在更新方法,只有更新的最後狀態,如果狀態實際上已經改變了:

AnimatorStates lastState = AnimatorStates.IDLE; 
public void PlayState(AnimatorStates state) 
{ 
    if(state != lastState) 
    { 
     string animName = string.Empty; 
     switch (state) 
     { 
      case AnimatorStates.WALK: 
       animName = "Walk"; 
       break; 
      case AnimatorStates.RUN: 
       animName = "Run"; 
       break; 
     } 
     if (_anim == null) 
      _anim = GetComponent<Animator>(); 

     _anim.Play(animName); 

     lastState = state; 
    } 
} 
+0

我怎麼使用它,然後在更新功能?如果我選擇WALK狀態,如何包括狀態WALK。有3個州。 –

+0

我給'PlayState'方法建議的更改將確保'_anim'不會對'_anim'進行任何操作,除非給予'PlayState'的狀態與最後一個狀態不同。這足以回答你的問題。 'WALK'狀態的工作方式與其他州在'PlayState'方法中工作的方式相同。但你只需要在'Update'方法中使用它。你剛纔沒有在你的示例代碼中使用它。 – Ibrahim