繁体   English   中英

是否有C#代码统一标识何时按下按钮以及何时释放按钮?

[英]Is there a C# code in unity to identify when a Button is pressed and when it is released?

我目前正在尝试在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命令中的按钮,它只会增大按钮的大小,而不会缩小按钮

使此脚本独占其On Click命令中的按钮

这毫无意义。 尤其是因为每隔一帧就一直调用Update方法。 因此,从onClick额外调用它会在该帧中调用两次。 也来自Button.onClick

请注意,在onClick之前调用EventType.MouseDownEventType.MouseUp


您可以例如使用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 PhysicsRaycaster上的点击检测,请确保将PhysicsRaycaster连接到了Camera。

当然,非UI对象也需要Collider

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

Input.GetMouseButtonDown

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

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

尝试使用Input.GetMouseButton(0)代替。

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

但是请注意,如果Input.GetMouseButton(0)处于循环中,则会检测到按下按钮的时间,因此会触发多次。

编辑通过触发器,我的意思是它返回True所以它将触发您的if

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM