【问题标题】:Unity 2D How to set touch button?Unity 2D如何设置触摸按钮?
【发布时间】:2021-02-18 13:59:42
【问题描述】:

我为 android 制作游戏,我需要在游戏屏幕上有 UI 操纵杆和 UI 攻击按钮。我已经有可用的操纵杆和键盘空格键上的攻击按钮。 有人能告诉我如何将代码从键盘输入切换到触摸输入吗? 附言对不起我的英语。

        if (Time.time >= nextAttackTime)
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Attack();
            nextAttackTime = Time.time + 2.5f / attackRate;
        }
    }

【问题讨论】:

标签: unity3d user-interface


【解决方案1】:

试试这个。

using UnityEngine;
using UnityEngine.UI;

public class Example : MonoBehaviour
{
    //Make sure to attach these Buttons in the Inspector
    public Button YourButton,

    void Start()
    {
        YourButton.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick(){ /// this method will active when press the button
       if (Time.time >= nextAttackTime)
       {
            Attack();
            nextAttackTime = Time.time + 2.5f / attackRate;
       }
    }
}

【讨论】:

  • 感谢您的回答!出现新错误“CS0079 事件“Button.onClick”只能出现在 += 或 -=" 的左侧
  • 已经修复了!我只是没有“使用 UnityEngine.UI;”非常感谢!
【解决方案2】:

另一种方法是使用统一的 Button 脚本,将其应用于表示 Button 的 GameObject。在目标图形下添加相应的图形对象。在 On Click() 下添加一个 Event,将具有您的 Attack Function 的游戏对象放入 (None Object) 并在 Function 下添加 Attack 函数。

以下是有关按钮工作原理的一些信息: https://docs.unity3d.com/2018.3/Documentation/Manual/script-Button.html

编辑:这里也回答了Unity Button code not working

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    相关资源
    最近更新 更多