Unity button control animation

Preparation: Download a free set of animation from Asset Store and import it into unity

Step 1: Create an empty objectCreate Empty

Inside the empty object GameObject

Add two buttons and pull in the Sword snd shie from Prefabs

 (The button is renamed and the description is omitted)

(A complete novice, you can download the same resource as me, Sword and Shield Pack)

 Step 2: Create the script and mount it on the empty GameObject

using UnityEngine;
using UnityEngine.UI;

public class ChacterC : MonoBehaviour
{     public Animator animator; // Animation controller     public Button idleButton; // Standby button     public Button attackButton; // Attack button


    private void Start()
    {         // Add OnClick event to the idle button         idleButton.onClick.AddListener(OnIdleButtonClick);
        

        // Add the OnClick event to the attack button
        attackButton.onClick.AddListener(OnAttackButtonClick);
    }

    public void OnIdleButtonClick()
    {
        animator.SetBool("Idle", true);
        animator.SetBool("Attack_01", false);
    }

    public void OnAttackButtonClick()
    {
        animator.SetBool("Idle", false);
        animator.SetBool("Attack_01", true);
    }
}

Step 3: Put the corresponding objects in

Step 4: Add button click objects to the two buttons

Step 5: Open the animation and animator windows

Step 6: Add two bool type variables, the names must be the same as the code

 

(The name is so long that the 1 after the 0 is not displayed)

Right-click Make Transition to create an arrow

 

 

Step 7: Set animation-related properties

Click another arrow for the same reason

 Just run it last

 

You can open the animator window to see if the animation converts normally when the button is clicked.

The cute new sharing is finished! Hope this helps you!

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_51741118/article/details/130953191