首页 > 解决方案 > Unity 3d:如何通过单击在 UI 工具包上设计的 UI 中的按钮在我的角色上显示动画?

问题描述

我在 Unity 3D 的 UI 工具包上设计了这个 UI。在此处输入图像描述

当我单击 UI 上的每个按钮时,我希望我的角色执行不同的动画。我已经用所需的剪辑和一个名为“deporteAn”的布尔变量设置了一个动画师。另外,我有我的 UIController 脚本,在其中我用它们的 UI 名称初始化了所有按钮,然后我调用了一个在单击按钮时执行操作的方法。如此代码所示:

public class UIController : MonoBehaviour
{
    public Button deporteButton;
    public Button lecturaButton;
    public Button trabajoButton;
    public Button vacunacionButton;
    public Button gatoButton;
    public Button perroButton;
    public Button ratonButton;

    private void OnEnable()
    {
        deporteButton = rootVisualElement.Q<Button>("deporte-button");
        lecturaButton = rootVisualElement.Q<Button>("lectura-button");
        trabajoButton = rootVisualElement.Q<Button>("trabajo-button");
        vacunacionButton = rootVisualElement.Q<Button>("vacunacion-button");

        gatoButton = rootVisualElement.Q<Button>("gato-button");
        perroButton = rootVisualElement.Q<Button>("perro-button");
        ratonButton = rootVisualElement.Q<Button>("raton-button");


        deporteButton.clicked += DeporteButton_clicked;//calling the method when deporteButton is clicked.

        public void DeporteButton_clicked()//Method where the animation should be displayed.
        {
            //Shows the animation on my character.
            animator.SetBool("deporteAn", true);
            UnityEngine.Debug.Log("Deporte clicked");
        }
    }
}

我认为问题可能是该脚本附加到 UIDocument。我试图将它附加到角色游戏对象上,但它没有用。我认为可能创建另一个脚本,将其附加到角色游戏对象并调用那里的方法可以工作,所以我这样做了:

public class PlayerController : MonoBehaviour

{
   
    public UIController uiButton;

    public void Start()
    {
        AnimationButtons();
    }
    public void AnimationButtons()
    {
        uiButton = GetComponent<UIController>();

        if (uiButton)
        {
            uiButton.deporteButton.clicked += uiButton.DeporteButton_clicked;
            UnityEngine.Debug.Log("Button pressed");
        }
        else
        {
            UnityEngine.Debug.Log("Button not pressed");
        }
    }

}

但它只显示“未按下按钮”并且在游戏视图中什么也不做。我能做些什么?或者我做错了什么?

标签: c#unity3dunity-ui

解决方案


从我的头顶开始,uiButton 变量为空,所以总是会写“未按下按钮”

在我的图片中查看@此代码,我认为您的代码中也会出现同样的错误

在此处输入图像描述

所以检查是否UIControllerPlayerController 附加到同一个游戏对象


推荐阅读