Simpler Way To Play Animation for Vuforia (2021 Update)

Okay, you want to play an animation, then nooooooo………..the model has more than one animation, so what do you do? Do you go through the process and create transitions, add parameters and do all of that? No you don’t need to actually. This is a handy tool for doing things fast. Here is the download link, and also as usual the explanation part of it, coz what use is things that you don’t understand or learn from?

How to use

  1. Add the Animation Player script to your model, it will give you the names of the animation clip

2. Call PlayAnimation using Vuforia Default Trackable Event Handler or Button

3. Type in the name of the animation you want to play in the slot. Done! When your ImageTarget is detected, the animation will play.

The Editor Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;


[CustomEditor(typeof(AnimationPlayer))]
public class AnimationPlayerEditor : Editor
{
    AnimationPlayer myTarget;
    UnityEditor.Animations.ChildAnimatorState[] states;

    public override void OnInspectorGUI()
    {
        // Assign the script to this inspector so that we can play with its properties
        myTarget = (AnimationPlayer)target;
        // create the menu and add items to it
        GenericMenu menu = new GenericMenu();
        
        GetAnimatorStates();

        GUILayout.Label("Animation State Name From Model:");

        foreach(UnityEditor.Animations.ChildAnimatorState b in states)
        {
          GUILayout.Label(b.state.name);
        }


    }

    void GetAnimatorStates()
    {
        // Get a reference to the Animator Controller:
        UnityEditor.Animations.AnimatorController animatorController = myTarget.GetTargetAnimator().runtimeAnimatorController as UnityEditor.Animations.AnimatorController;

        // States on layer 0:
        UnityEditor.Animations.AnimatorStateMachine stateMachine = animatorController.layers[0].stateMachine;
        states = stateMachine.states;
        
    }



}

The Script (called AnimationPlayer)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class AnimationPlayer : MonoBehaviour
{
    Animator animator;
    // Start is called before the first frame update
    void Start()
    {
        animator = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public Animator GetTargetAnimator()
    {
        if(animator == null)
        {
            animator = gameObject.GetComponent<Animator>();
            return animator;
        }
        else
        {
            return animator;
        }
        
    }

    public void PlayAnimation(string animationName)
    {
        if(animationName != "")
        {
            animator.StopPlayback();
            animator.Play(animationName);
        }

        
    }


}

The Explanation

This script has two parts. The first part is the editor extension. The reason we need the editor extension is to access the Animator’s Editor properties in order for us to extract the animation state names. This information is only available through UnityEditor.Animations.AnimatorController.

The second part is the script itself. We need this script to be two things, one is to become the interface that our editor script will rely on to get the reference to the Animator. The second function is for us to ask the animator to play our animation of choice.

Simpler Vuforia Event Handling using Unity Events

Edit 2021 Update:

Notice, this codes are no longer needed as Vuforia has provided their own Unity Events Handler. So If you are using the latest Vuforia, it comes built in. It looks like the picture below and it works exactly the same as the one I wrote here.

This post below is still kept as there are people still struggling to update their old projects, so this is for you guys/gals in University, hope you can update soon!


Do you ever wish that Vuforia event handling is as simple as using the OnClick() property in Unity UI’s Button? Wish no more bros and sis. Here the code, and explanation on how I did it.

The Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using Vuforia;

    public class EasyEventHandler : MonoBehaviour, ITrackableEventHandler
    {

    public UnityEvent onMarkerFound;
    public UnityEvent onMarkerLost;

        protected TrackableBehaviour mTrackableBehaviour;
        protected TrackableBehaviour.Status m_PreviousStatus;
        protected TrackableBehaviour.Status m_NewStatus;



        protected virtual void Start()
        {
            mTrackableBehaviour = GetComponent<TrackableBehaviour>();
            if (mTrackableBehaviour)
                mTrackableBehaviour.RegisterTrackableEventHandler(this);
        }

        protected virtual void OnDestroy()
        {
            if (mTrackableBehaviour)
                mTrackableBehaviour.UnregisterTrackableEventHandler(this);
        }


        public void OnTrackableStateChanged(
            TrackableBehaviour.Status previousStatus,
            TrackableBehaviour.Status newStatus)
        {
            m_PreviousStatus = previousStatus;
            m_NewStatus = newStatus;

            if (newStatus == TrackableBehaviour.Status.DETECTED ||
                newStatus == TrackableBehaviour.Status.TRACKED ||
                newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
            {
                onMarkerFound.Invoke();
            }
            else if (previousStatus == TrackableBehaviour.Status.TRACKED &&
                     newStatus == TrackableBehaviour.Status.NO_POSE)
            {
 
                onMarkerLost.Invoke();
            }
            else
            {
            // For combo of previousStatus=UNKNOWN + newStatus=UNKNOWN|NOT_FOUND
            // Vuforia is starting, but tracking has not been lost or found yet
            // Call OnTrackingLost() to hide the augmentations
            onMarkerLost.Invoke();
            }
        }
    }

How it looks like

Explanation

Creating the Unity Events and Exposing it in Inspector

This code uses the UnityEngine.Events . Firstly, I create two UnityEvents variable, and make the variables public, doing this I get to expose the events, giving you that familiar On Click () thingy in Unity UI Button.

    public UnityEvent onMarkerFound;
    public UnityEvent onMarkerLost;

Invoking the Events when marker is detected and lost

Then, OnTrackableStateChanged, if the Image Target is detected, I use the UnityEvent’s Invoke() function to Invoke the event, this will then work just like the On Click ()

That’s all folks…… enjoy!