- Home /
Play a clip from a different animation controller with a UnityEvent?
I have a script that I am putting on an animation clip of my character animator to allow me to pass events when certain animations play or stop.
public enum PlayCondition{OnEnter, OnUpdate, OnExit}
public class AnimStateMachineEvent : StateMachineBehaviour
{
public PlayCondition condition;
public UnityEvent onAnimationConditionMet;
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
// may need to add something to make sure this fires each time an animation loop restarts?
if(condition != PlayCondition.OnEnter) return;
Execute();
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if(condition != PlayCondition.OnUpdate) return;
// may need a condition to smooth between events?
Execute();
}
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if(condition != PlayCondition.OnExit) return;
Execute();
}
private void Execute()
{
onAnimationConditionMet.Invoke();
}
That seems to work for many events but I can't seem to call an animation clip from a different objects animator. Im not sure if I need an Event override that takes an int so I can reference parameter on the other objects animation or a whole other script to set the parameter but I'm hoping I can set the clip and let it play so the two animations can synchronize.
The other tree is very simple with a single parameter "clipCount" setting an int between each clip
EDIT: I made and tested a simple script to change the animation clip. public Animator anim; public int clipNumber = 0;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update() //It may be beter to call this rather then run on update.
{
switch(clipNumber)
{
case 1:
Debug.Log("Animation Start");
anim.SetInteger("clipInt",clipNumber);
break;
case 2:
Debug.Log("Animation Loop");
anim.SetInteger("clipInt",clipNumber);
break;
case 3:
Debug.Log("Animation Stop");
anim.SetInteger("clipInt",clipNumber);
break;
case 4:
anim.SetInteger("clipInt",0);
break;
default:
anim.SetInteger("clipInt",0);
break;
}
}
However I still cant call the script in the StateMachineBehaviour's UnityEvent. It seems that event cant trigger things that are not on that object?
Anyone know a way around this?