【问题标题】:Why won't Unity SetActive execute within Input.GetButtonDown()?为什么 Unity SetActive 不能在 Input.GetButtonDown() 中执行?
【发布时间】:2018-03-31 18:22:29
【问题描述】:

我完全被这个难住了。我在游戏中有一本书,当您在其一定距离内朝其大致方向看时并按下操作按钮(e 或鼠标左键),它应该显示一个 UI 面板(bookPage)。这是我的代码。

void Update () {
    Vector3 direction = player.transform.position - this.transform.position;
    angle = Vector3.Angle (direction, player.transform.forward);
    distance = direction.magnitude;
    if (angle >= 160 && distance <= 2 && !bookPage.activeSelf) {
        if(Input.GetButtonDown("Action")) {
            bookPage.SetActive (true);
        }
    }
    if (bookPage.activeSelf && Input.GetButtonDown("Action")) {
        bookPage.SetActive (false);
    }
}

这不起作用。具体来说,将页面设置为活动的行不起作用。如果它打开,它将正确关闭。如果我复制并粘贴bookPage.SetActive (true); 除了if(Input.getButtonDown("Action")){} 之外,此方法中的任何位置都会使 bookPage 处于活动状态。如果我将Debug.Log("message"); 放在该 if 语句中,它将显示在控制台中。这只是将 bookPage 设置为活动的一行不起作用。我不知道为什么。我尝试将其移至不同的方法,然后调用它并执行相同的操作,但使用协程。都没有奏效。我也尝试使用其他有效的键,但我需要它与操作键一起使用。还值得注意的是,操作键可用于其他用途。我已经用它来开门了。有没有其他人遇到过这样的问题?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    当您调用 SetActive(true) 时,activeSelf 将为您的第二个条件返回 true,该条件将在之后立即调用 SetActive(false)

    改变这个;

    if (angle >= 160 && distance <= 2 && !bookPage.activeSelf)
    {
        if (Input.GetButtonDown("Action"))
        {
            bookPage.SetActive(true);
        }
    }
    if (bookPage.activeSelf && Input.GetButtonDown("Action"))
    {
        bookPage.SetActive(false);
    }
    

    到这个;

    if (angle >= 160 && distance <= 2 && !bookPage.activeSelf)
    {
        if (Input.GetButtonDown("Action"))
        {
            bookPage.SetActive(true);
        }
    }
    else if (bookPage.activeSelf && Input.GetButtonDown("Action"))
    {
        bookPage.SetActive(false);
    }
    

    【讨论】:

    • 非常感谢。我一直盯着这个太久了,无法弄清楚我做错了什么。
    • @DavidMenear 如果这个答案解决了你的问题,别忘了accept它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2010-10-08
    • 1970-01-01
    • 2021-12-05
    • 2020-09-11
    相关资源
    最近更新 更多