按下按钮时启动动画不起作用

Start animation on button press not working

对于我最近的项目,如果用户在它前面并按下 "e",我需要打开一扇门。

这是按钮的代码:

using UnityEngine;

public class Button : MonoBehaviour
{

    public Animator Door; // In the editor, give a reference to your door. It     must have an Animator script for this to work

    void OnTriggerEnter(Collider c)
    {
        if (c.gameObject.tag == "Player")
        {
            //Text = "E to interact!" 

            if (Input.GetKeyDown("e"))
            {
                print("´Test");
                GetComponent<Animator>().SetTrigger("OnPress"); // The button's animator goes to "pressed" state
                Door.SetTrigger("Open");  // The door's animator goes to "open" state
            }
        }
    }
}

动画师看起来像这样:

从闲置到开放的转变:

按钮上附有门:

所以我在这里遇到了两个问题,第一个是 - 使用上面的代码,如果我按 E,则没有任何反应。没有错误,没有任何操作。 如果我删除 Input.GetKeyDown("e") 并将 Button-Mesh 设为触发器并在其中添加 运行,它会显示

MissingComponentException: There is no 'Animator' attached to the "Button" game object, but a script is trying to access it. You probably need to add a Animator to the game object "Button". Or your script needs to check if the component is attached before using it.

如果您需要更多信息,请告诉我。谢谢!

好的,您的交互方式是错误的。首先,On trigger enter 只会工作一次。那是你进入触发器的时候。所以它不会接受按键事件。您必须将代码移到 OnTriggerStay(Collider col) 中,它会经常被调用。如果它需要任何关键事件,那么它就会启动。这将解决您的问题 1.

至于第二个问题,我敢肯定你是从别处复制粘贴这段代码的。只有 canvas UI 按钮具有动画状态。你的按钮是普通网格而不是 UI 那个。因此在该代码中设置状态按钮将不起作用,即

GetComponent<Animator>().SetTrigger("OnPress"); // The button's animator goes to "pressed" state

除非您使用 Canvas 按钮,否则脚本不起作用。并且错误描述中已经提到了你的错误 Button Mesh Does not have an animator。尝试注释该行,看看它是如何工作的。

编辑:

我完成了你的转换你的代码应该是

door.GetComponent<Animator>().SetTrigger("OnPress"); 

而不是

GetComponent<Animator>().SetTrigger("OnPress");

因为它正在尝试调用门动画器的 OnPress 状态。如果有任何问题,请在下面评论并提供更多信息。抱歉没有先注意到这个。