- Home /
[SOLVED]How to set the animator's controller in an editor script?
I'm creating a prefab from an gameobject via script, and I want to add an animator component and set its controller property.
I tried this:
myObject.GetComponent<Animator>().runtimeAnimatorController = myAnimator as RuntimeAnimatorController;
But when I create the prefab, the field remains empty. I figured that the actual controller property is private, but is there a way to change it within the editor?
EDIT I eventually got it to work after deleting and re-creating the Animator asset. Not sure what happened, but problem solved.
Why are you casting to RuntimeAnimatorController with an "as". Are you sure that its a RuntimeAnimatorController?
Also if you create it using "new" such as animator.runtimeAnimatorController = new RuntimeAnimatorController();
then when you make it into a prefab then it wont persist.
If you create a RuntimeAnimatorController in the project via "Create -> Animator Controller", then assigning it to the Animator component will persist.
In my example, 'myAnimator' is an AnimatorController present in the project files as an asset, it already exists; but it won't persist nonetheless. I assumed there would be a utility editor class to set the Animator's controller property, but I can't seem to find one.
Look I tried to do this and it works. After setting an animator;s controller via script, the controller stays there after it becomes a prefab.
You are doing something else that we dont know about, Are you sure that after assigning the Animator its controller, that the controller is a Project asset? Try clicking the controller field in the inspector, see if it redirects to a project asset.