Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Editor, not Runtime: How to get AnimatorController reference within StateMachineBehaviour

Discussion in 'Animation' started by Fressbrett, Dec 8, 2022.

  1. Fressbrett

    Fressbrett

    Joined:
    Apr 11, 2018
    Posts:
    79
    Hi everyone,

    is there a way to grab the AnimatorController reference within a StateMachineBehaviour within the Editor, i.e. not during runtime?

    Use case:
    I want to create a dropdown displaying all parameters of the AnimatorController using OdinInspector's ValueDropdown attribute within the Inspector of my StateMachineBehaviour, to avoid having to copy over all the names manually.


    Thanks for any tips!
    - Fressbrett
     
  2. Yuchen_Chang

    Yuchen_Chang

    Joined:
    Apr 24, 2020
    Posts:
    35
    The added StateMachineBehaviour is actually a ScriptableObject, and is also a subset of the AnimatorControllor.
    So you can do something like this:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. #if UNITY_EDITOR
    4. using UnityEditor;
    5. using UnityEditor.Animations;
    6. #endif
    7.  
    8. public class SomeBehaviour : StateMachineBehaviour
    9. {
    10.     [SerializeField] private bool someBool;
    11.  
    12.     private void OnValidate()
    13.     {
    14.         // or some other function that will be called when you need your parameters.
    15. #if UNITY_EDITOR
    16.         var path = AssetDatabase.GetAssetPath(this);
    17.         var animatorController = AssetDatabase.LoadMainAssetAtPath(path) as AnimatorController;
    18.         var parameters = animatorController.parameters;
    19.         // parameters is Type: AnimatorControllerParameter[]
    20.  
    21.         int idx = 0;
    22.         foreach (var parameter in parameters) {
    23.             Debug.Log($"parameter #{idx}: {parameter.name}");
    24.             idx++;
    25.         }
    26. #endif
    27.     }
    28. }
     
    Fressbrett likes this.
  3. Fressbrett

    Fressbrett

    Joined:
    Apr 11, 2018
    Posts:
    79
    Awesome, thanks, that sounds intuitive! I will then cache the reference and only load it when my reference is null