【问题标题】:Need a way to use button click functionality vs GetKeyDown in Coroutine需要一种在协程中使用按钮单击功能与 GetKeyDown 的方法
【发布时间】:2021-04-21 16:35:45
【问题描述】:

这个动画脚本可以工作,但是,我需要使用移动设备的 UI 按钮来代替 WHILE LOOP 中的 Keycode 输入,但我无法弄清楚。我找到了一个关于在它周围放置一个包装器以使方法可用于单击事件的答案,但不知道它应该如何在更新函数中工作。作为unity和c#的新手,我花了很长时间才走到这一步,所以如果你能提供详细的答案或建议,我可以恢复我的生活,如果可以,请提供帮助。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using SWS;

public class goat_question : MonoBehaviour
{
    private Animator anim;
    public GameObject player;
    public Text ResultText;
    public Text AnswerText;  
    public Text AnswerText2;
    public Button GoatButton;

  

    void Start()
    {
        anim = GetComponent<Animator>();
        Button btn = GoatButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);

    }

    void TaskOnClick()
    {
        Debug.Log("You have clicked the button!");
    }
   
    // Update is called once per frame
    void Update()

    {
        if (AnswerText.text.Equals(AnswerText2.text))

        {                                         

            StartCoroutine(GoatWalkPathCoroutine());        

        }

         IEnumerator GoatWalkPathCoroutine()
        {
            while (true)  
            {              

                    if (Input.GetKeyDown(KeyCode.K))  
                {
                    anim.Play("goat_hi_walk");
                    player.GetComponent<splineMove>().enabled = true;
                    yield return new WaitForSeconds(27);
                    anim.Play("goat_hi_licking");

                }
                yield return null;
            }

        }

    }

}

【问题讨论】:

  • 我将提交我的评论作为答案
  • Ty Irvine,我不知道你是否看过我的描述。该代码有效,并且该函数的调用与您的更新完全相同,与我的更新完全相同。问题不在于协程运行,而是我在 while 循环中使用的 CONDITION 是 Keycode,它不适用于移动设备。我需要使用 UI Button 并且不知道如何让按钮单击以在协程中工作,或者解决方法是什么。这个问题没有解决。请看标题。协程运行良好。这是关于需要用 ui 按钮单击替换 Keydown/keycode。谢谢。未解决。
  • 我很抱歉。我删除了我的答案。我误读了这个问题。贾斯汀的回答是否为您解决了这个问题?
  • Ty,是的。感谢您尝试提供帮助。非常感谢,

标签: unity3d button coroutine keycode animator


【解决方案1】:

在仅用于 UI 按钮的单独脚本中,有一个名为 isClicked 或其他东西的布尔值,并在单击按钮时将其设置为 true。在这个主脚本中,您可以引用刚刚创建的那个,而不是 Input.GetKey,您可以说 if(otherScript.isClicked)

【讨论】:

  • 我确定这是答案,但正如我所说,我是 c# 和统一的新手。我创建了脚本并添加了此代码,它在我的动画脚本中创建了一个错误。我确定这很简单。public class isClickedGoat : MonoBehaviour { public bool isClicked;公共无效 OnButtonClick() { isClicked = true; } }
猜你喜欢
  • 2021-04-16
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多