Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c# - How to have a button run while it is being pressed

Im trying to have a method continuously run while a button is pressed. At the moment the method only runs once when the UI button is pressed. I've tried implementing a coroutine but I couldn't figure out a way a condition for StopCoroutine() to run. I've also tried using the event triggers PointerUp and PointerDown that set a boolean to false and true that determine if a coroutine runs or not but that seemed to work. Would anyone know how to implement a continuous on button hold? Any help is appreciated.

The method I want to continuously run while the button is held. This method is called in a PointerDown event trigger in the UI button.

public void spawnLaser()
    {
        GameObject laser = Instantiate(laserprefab, transform.position, Quaternion.identity) as GameObject;
        laser.GetComponent<Rigidbody2D>().velocity = new Vector2(laserSpeed, 0);
    }
question from:https://stackoverflow.com/questions/65890340/how-to-have-a-button-run-while-it-is-being-pressed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Input.GetKeyDown returns true during the frame the user starts pressing down the key identified by name, while Input.GetKey returns true while the user holds down the key identified by name. Seems you need to give Input.GetKey a try.

To keep it calling while pressed, call it from the Update().

public void spawnLaser()
{
    GameObject laser = Instantiate(laserprefab, transform.position, 
    Quaternion.identity) as GameObject;
    laser.GetComponent<Rigidbody2D>().velocity = new Vector2(laserSpeed, 0);
}
void Update()
{
    if (Input.GetKey("up"))
    {
        print("up arrow key is held down");
        spawnLaser();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...