Monday, January 29, 2018

Adding and controlling 'Animator Controller' at runtime using script in Unity


Time to read: 5 min

Goal: To use particular animation with any game object at runtime.

Unique thing used: RuntimeAnimatorController class (specially designed by Unity for runtime use)



Steps: 
1. Create 'Animator Controller' in the 'Project view'.
2. Use drag and drop method or 'Load resources' method to take it into code. (Remember to type cast it into 'RuntimeAnimatorController' class when using load resources method)
3. Create 'animation' of your need.
4. Drag the animation into 'Animator Window' and make arrangements as shown below:


5. You have to create one 'default state' which does nothing, and set it as 'default state' because when you load the animator at runtime it will by default plays the current default state from the animator window. And if our animation is the default state then it will play that animation which we dont want, coz we want control on it.

6. We are going to control the animation using trigger. So create the new parameter in 'Animator Window' as 'fade' of type trigger.

7. Triggers are basically used to tell the animator which state transition should be played.

8. To assign the trigger variable as a 'condition' click on the 'transition arrow' which is starting from 'Base' to 'fadeOut' state.

9. You will see the properties as shown in below into the 'inspector window':


10. Click on the plus sign in below 'conditions' section. And select the 'fade' variable. Now when we set the trigger to 'fade' from script using 'SetTrigger()', then this transition will happen and 'fadeOut' state will be played. When the animation is played then the control will go back to 'Base' state automatically coz we have made the transition arrow from 'fadeOut' to 'Base'. (Remember to uncheck the 'Loop Time' variable from the 'fadeOut' animations property so that it will not play in loop)

11. Below is the script:



If you have any doubt please drop a comment.

Thank you,
Happy coding :)


3 comments:

  1. Excellent work!!!
    I have been searching the solution about this for days!!!
    Congratulations!!!

    ReplyDelete
  2. Hello, I have a soldier with a healthy state and an injured state, when starting the game there must be one injured (with its respective animation) and another healthy (with its respective animation) I already have the 2 controllers but I don't know how to make them healthy be healthy with animation and the injured with animation of wounded

    ReplyDelete