user15532639
user15532639

Reputation:

Hold down UI button to perform an action in unity

I'm making a simple game in unity, and I decided to make it able to be played on mobile, so to move a cube I use the AddForce method inside of the update method, but now I added two buttons to move the cube, but the problem is that I have to make the action on a hold function instead of click one, so how is that done in unity? something like this but with a button hold...

if (Input.GetKey("a") || Input.GetKey("[4]") || Input.GetKey("left"))
    {
        rb.AddForce(-sideWaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

And I'm using Unity 2020.

Upvotes: 0

Views: 1106

Answers (1)

DavidA_
DavidA_

Reputation: 93

What you can do is you can add a rigidbody to the cube and make a script for the ui canvas. Once you done that, you can reference the cube like this : public GameObject cube;. Then in the update function what you can do is add some if statements checking if either button is pressed. And if for example the button that makes the cube move left is pressed, add a force to the cube on the x axis. I can give you a hint on how to do this : cube.GetComponent<Rigidbody>().AddForce(15, 0, 0). I'm sure you can figure the rest out by yourself.

I hope you found this useful! :D

Upvotes: 0

Related Questions