unity run a function as long a button is pressed in the inspector

廉价感情. 提交于 2021-02-05 10:54:05

问题


I'm a newbie in Unity

Using Unity Inspector i have setup a button that makes a callback to a function (OnClick), it works fine but only once, to fire the action again i need to release and click the button again

How can i make that the function keeps running over and over as long as the button is pressed? (like a machine gun)

public void MoveLeft ( )
{
    transform.RotateAround(Camera.main.transform.position, Vector3.up, -rotation / 4 * Time.deltaTime);
    infopanel.RotateAround(Camera.main.transform.position, Vector3.up, -rotation / 4 * Time.deltaTime);
}

Regards...


回答1:


The OnClick can't do this. Use OnPointerDown and OnPointerUp. Set a boolean variable to true/false in these function respectively then check that boolean variable in the Update function

Attach to the UI Button object:

public class UIPresser : MonoBehaviour, IPointerDownHandler,
    IPointerUpHandler
{
    bool pressed = false;

    public void OnPointerDown(PointerEventData eventData)
    {
        pressed = true;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        pressed = false;
    }

    void Update()
    {
        if (pressed)
            MoveLeft();
    }

    public void MoveLeft()
    {
        transform.RotateAround(Camera.main.transform.position, Vector3.up, -rotation / 4 * Time.deltaTime);
        infopanel.RotateAround(Camera.main.transform.position, Vector3.up, -rotation / 4 * Time.deltaTime);
    }
}

You can find other event functions here.



来源:https://stackoverflow.com/questions/46374285/unity-run-a-function-as-long-a-button-is-pressed-in-the-inspector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!