【问题标题】:Is there a C# code in unity to identify when a Button is pressed and when it is released?是否有统一的 C# 代码来识别按钮何时被按下和何时被释放?
【发布时间】:2019-05-29 22:14:19
【问题描述】:

我目前正在尝试在 C# 中设置一个代码,以识别何时按下某个按钮以及何时释放它

我试图让这个按钮在按下时缩小,在释放时放大

public class clickshake : MonoBehaviour
{
    public GameObject click;
    public void Update()
    {    
        if (Input.GetMouseButtonDown(0))
        {
           transform.localScale += new Vector3(-0.1F, -0.1f, 0);
        }
        if (Input.GetMouseButtonUp(0))
        {
           transform.localScale += new Vector3(0.1F, 0.1f, 0);
        }
    }
}

通过在其 On Click 命令中使该脚本独占按钮 它只是增大了按钮的大小,并没有缩小它

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    使该脚本在其 On Click 命令中专属于按钮

    这没什么意义。特别是因为Update 方法在每一帧都被调用。因此,从onClick 额外调用它会在该帧中调用它两次。同样来自Button.onClick

    请注意,EventType.MouseDownEventType.MouseUponClick 之前被调用。


    你可以例如使用IPointerDownHandlerIPointerUpHandler 接口来实现它

    public class clickshake : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
    {
        //Detect current clicks on the GameObject (the one with the script attached)
        public void OnPointerDown(PointerEventData pointerEventData)
        {
            transform.localScale -= new Vector3(0.1F, 0.1f, 0);
        }
    
        //Detect if clicks are no longer registering
        public void OnPointerUp(PointerEventData pointerEventData)
        {
            transform.localScale += new Vector3(0.1F, 0.1f, 0);
        }
    }
    

    注意

    确保场景中存在EventSystem 以允许点击检测。对于非 UI GameObjects 上的点击检测,请确保将 PhysicsRaycaster 附加到相机。

    当然,非 UI 对象也需要Collider

    【讨论】:

    • 非常感谢,代码运行良好,感谢您的帮助
    【解决方案2】:

    Input.GetMouseButtonDown(0)在按钮按下时触发,因为您在按钮已按下时调用它,它不会触发。

    Input.GetMouseButtonDown

    在用户按下给定鼠标按钮的帧期间返回 true。

    https://docs.unity3d.com/ScriptReference/Input.GetMouseButtonDown.html

    请尝试改用Input.GetMouseButton(0)

    或者在OnClick()以外的其他地方调用它。

    但请注意,Input.GetMouseButton(0) 如果在循环中,将触发多次,因为它检测到何时按下按钮。

    编辑 触发我的意思是它返回True 所以它会触发你的if

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多