Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

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:
    101
    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
     
    thepersonguy123 likes this.
  2. Yuchen_Chang

    Yuchen_Chang

    Joined:
    Apr 24, 2020
    Posts:
    129
    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:
    101
    Awesome, thanks, that sounds intuitive! I will then cache the reference and only load it when my reference is null