An easy way to trigger animations by code is to set up a trigger, set it as the condition for the transition, and trigger it with animator.SetTrigger()
.
Setting up a Trigger
Looking at the Animator window, you should see a tabbed window to the left of the controller chart. Select the "Parameters" tab. Click on the button marked + and select "Trigger". Give it a meaningful name, and your done.
If you are missing the "Layers / Parameters" window, check for a closed eyelid (), along the same bar. Clicking this button unfolds the window.
Setting up the Transition
On the transition to the desired animation, in your case "stepBreak" and in my case "twitch", you will find the trigger you made listed under the "Conditions" option. Select your trigger, and set it as the only condition.
Depending on your circumstance, you probably want to set up a transition in the opposite direction. Given that you are animating something being broken, I would assume you probably wouldn't transition back to the mended state. Either way, you can set (or not set) your additional transitions up however you want.
Triggering the Trigger
Now everything is set up, all you need to do is grab a reference to the specific Animator
instance attached to the game object, and call animator.SetTrigger(triggerName)
where triggerName
is the name you gave to the trigger you just created and set up.
I've done mine using the UnityEditor
namespace to give me a quick and easy button to click from the Inspector:
using UnityEngine;
using UnityEditor;
public class TriggerAnimator : MonoBehaviour
{
// Reference to the Animator, which I add from the Inspector.
public Animator animator;
}
[CustomEditor(typeof(TriggerAnimator))]
public class TriggerAnimatorEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector()
TriggerAnimator triggerAnimator = (TriggerAnimator)target;
// If the created button "Animate" is clicked,
if (GUILayout.Button("Animate"))
{
// Set off the trigger "twitch" on the animator in triggerAnimator.
triggerAnimator.animator.SetTrigger("twitch");
}
}
}
You would probably use something more simple, like this:
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
animator.SetTrigger("stepBreak")
}
}
That's all there really is to it.