Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question AnimatorController is UnityEditor ONLY. Why?

Discussion in 'Animation' started by Demexis, Aug 24, 2023.

  1. Demexis

    Demexis

    Joined:
    Jul 7, 2021
    Posts:
    15
    I needed to find out the length of the animation by the name of the state in the animator.

    Here is the solution I came up with:
    Code (CSharp):
    1. using System;
    2. using UnityEditor.Animations;
    3. using UnityEngine;
    4.  
    5. public static class AnimatorExtensions {
    6.     public static float GetLengthOfState(this Animator animator, string stateName) {
    7.         if (animator.runtimeAnimatorController is not AnimatorController animatorController) {
    8.             throw new Exception("Given animator has no AnimatorController.");
    9.         }
    10.            
    11.         foreach (var animatorControllerLayer in animatorController.layers) {
    12.             foreach (var childAnimatorState in animatorControllerLayer.stateMachine.states) {
    13.                 if (childAnimatorState.state.name == stateName) {
    14.                     if (childAnimatorState.state.motion is AnimationClip animationClip) {
    15.                         return animationClip.length / childAnimatorState.state.speed;
    16.                     }
    17.                 }
    18.             }
    19.         }
    20.  
    21.         throw new Exception("Couldn't find a state named as <color=yellow>" + stateName + "</color>");
    22.     }
    23. }
    This is a very useful method that returns me the exact time after which I execute the rest of the logic.

    When building the project, the compiler complains about the
    UnityEditor
    namespace, which is not included in the build.

    And what should I do now? Why can't I use what the game already uses?

    Are there any other similar methods? I would really hate to hardcode the animation duration value.