Unity script communication for animations
Objective: Communicate between the player script and the player animation script to change the player animations
In the 2D mobile game that I am currently working on I decided to take the animations out of the player controller class and have them contained in their own separate class script.
I did this so that if in the future I want to change when I call the animations I only have to change the calling and not the implementation. It will also help me keep track of what animations I am using and will let anyone else on the project know where the animations are.
I first need to know about the animator that is attached to the player. I have used a serializedfield as using get component uses up processing power each time it is called. I manually set this in the Unity editor once the script has been saved.
My current animation script looks as above with separate method calls that handle the changing of the player animations.
For the move animation I need to be able to know the speed that the player is moving so that I can adjust the animation. I pass in the current speed from the player class to the animations script.
I needed something similar for the jumping animation to play. Instead of having a variable that I update inside the player animation class for if the player can jump or not. I decided that I would just pass in the current state of the bool from the player and have a simple method call. This way I can pass in whether it is true or not.
In the player class I just needed to get a reference to the PlayerAnimation script and then just to call the relevant methods with their parameters, when I want my animations to play.
I have an attack method that is run in the Update. If the left mouse button is clicked and the player is grounded, then play the attack animation.
You can see above a small snippet of the current animator and how it’s changing animations.