I have not very much experience regarding editor scripts so there is probably something very obvious I'm missing. Hopefully someone can give me a hand with this.
I'm trying to write a very simple editor script for a MonoBehaviour which includes an animator. The idea is to show in the inspector tab a Popup window with all the triggers in the Animator so anyone can be selected and then saved in a string variable in the MonoBehaviour script. The final goal for this is to create a prefab with any given animator and this MonoBehaviour script that can be instantiated multiple times in any scene, then select specific triggers in the Popup window to make the animator go through different transitions.
My classes are like this:
[CustomEditor(typeof (AnimationScript))]
public class AnimationScript_Editor : Editor
{
public override void OnInspectorGUI()
{
this.DrawDefaultInspector();
AnimationScript targetObject = (AnimationScript) this.target;
var indexProperty = serializedObject.FindProperty("selectedIndex") ;
var triggerNameProperty = serializedObject.FindProperty("m_selectedTrigger");
Animator animator = targetObject.p_Animator;
if (animator == null)
return;
List<string> triggerOnlyNames = animator.parameters.ToList().FindAll(x => x.type == AnimatorControllerParameterType.Trigger)
.Select(x => x.name).ToList();
triggerNameProperty.stringValue = triggerOnlyNames[indexProperty.intValue];
indexProperty.intValue = EditorGUILayout.Popup(indexProperty.intValue, triggerOnlyNames.ToArray());
serializedObject.ApplyModifiedProperties();
}
}
public class AnimationScript : MonoBehaviour
{
//public MyEnum animationList;
[ContextMenu(" test play animation")]
private void Update()
{
Debug.Log("---> " + m_selectedTrigger);
}
public Animator p_Animator => m_Animator;
[SerializeField] private Animator m_Animator;
public string m_selectedTrigger = "none";
public int selectedIndex = 0;
}
Is working as expected, the list of triggers is loaded as a list of strings in the Popup and I can select any of them. I can even run the editor after doing that and I see in the Debug.Log from Animation.Update the very same selected string.
However, something weird happens when I try to save the scene by going to File-->save after making a selection (which is the ultimate goal of this),I get an exception: 'ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.'
Now, this happens exactly in the line
triggerNameProperty.stringValue = triggerOnlyNames[indexProperty.intValue];
and when I go step by step I see that animator.parameters has a length of 0 so the exception itself makes perfect sense but I can't understand why that happens. I also noticed that, despite the exception, if I close the scene and then load it again the change was properly saved and tthere is no exceptions anymore.
Can anybody give me a glimpse of why is this hapening and, hopefully, how to make it work properly??
Thanks in advance