Skip to content

Instantly share code, notes, and snippets.

@Protonz
Last active July 18, 2017 21:35
Show Gist options
  • Save Protonz/a909aad3f73054ceb7718576c21adc34 to your computer and use it in GitHub Desktop.
Save Protonz/a909aad3f73054ceb7718576c21adc34 to your computer and use it in GitHub Desktop.
Reacting to Animation State Changes
using UnityEngine;
using UniRx;
using UniRx.Triggers;
using System;
[RequireComponent(typeof(Animator))]
public class AnimationStateTest : MonoBehaviour {
void Start () {
var animator = GetComponent<Animator>();
animator.OnEnterState("Base Layer.AState")
.Subscribe(_ =>
Debug.Log("Entered AState")
).AddTo(this);
animator.OnEnterState("Base Layer.BState")
.Subscribe(_ =>
Debug.Log("Entered BState")
).AddTo(this);
// User input to change state machine state
// A
int AHash = Animator.StringToHash("A");
Observable.EveryUpdate()
.Where(_ => Input.GetKeyDown(KeyCode.A))
.Subscribe(_ =>
animator.SetTrigger(AHash)
).AddTo(this);
// B
int BHash = Animator.StringToHash("B");
Observable.EveryUpdate()
.Where(_ => Input.GetKeyDown(KeyCode.B))
.Subscribe(_ =>
animator.SetTrigger(BHash)
).AddTo(this);
}
}
public static class AnimationExtensions {
public static IObservable<ObservableStateMachineTrigger.OnStateInfo> OnEnterState( this Animator animator, string fullPath ) {
// Listen for state machine changes
var observableStateMachineTrigger = animator.GetBehaviour<ObservableStateMachineTrigger>();
if( observableStateMachineTrigger == null ) {
Debug.LogError("Missing ObservableStateMachineTrigger Behaviour", animator.gameObject);
return Observable.Empty<ObservableStateMachineTrigger.OnStateInfo>();
}
int fullPathHash = Animator.StringToHash(fullPath);
return observableStateMachineTrigger.OnStateEnterAsObservable()
.Where( onStateInfo => onStateInfo.StateInfo.fullPathHash == fullPathHash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment