Continuous action while pressing UI Button
I'll start by saying that I eventually accomplished what I wanted to do, but with quite a bit of a hassle and code. I'm wondering if there's another more efficient way.
What I want to do is quite simple. I have a UI Button and while I keep it pressed I want an object to rotate (actually 2 buttons, one for each direction). I have a function handling the rotation. The embedded OnClick method doesn't seem to do the trick, as it calls the method once and not for as long as I press the key.
I did some digging around and added an Event Trigger component to my button. Someone suggested I should add an UpdateSelected event and call my method, but this didn't work either, cause the method did start as soon as I pressed the button, but didn't stop when I released the button. I don't know if there's a fix for that.
I went on a different route, added a PointerDown and a PointerUp event, hoping I could control the rotation through a boolean variable (start the rotation when the boolean is true and stop when it's false). But that didn't seem to work either, as I didn't seem to have access to the boolean through the event trigger (setting them to static didn't help), leading me to create additional methods just to change the value of the boolean variable.
I ended up with this:
bool rotateCCW;
bool rotateCW;
public float speed = 100;
// Use this for initialization
void Start () {
fObjTransform = fProduct.GetComponent<Transform> ();
rotateCCW = false;
rotateCW = false;
}
// Update is called once per frame
void Update ()
{
if (rotateCCW) {
RotateCounterClockWise ();
} else if (rotateCW)
{
RotateClockWise ();
}
}
public void StartRotateCCW()
{
rotateCCW = true;
}
public void StopRotateCCW()
{
rotateCCW = false;
}
public void StartRotateCW()
{
rotateCW = true;
}
public void StopRotateCW()
{
rotateCW = false;
}
public void RotateClockWise()
{
fObjTransform.Rotate (Vector3.up * speed * Time.deltaTime);
}
public void RotateCounterClockWise()
{
fObjTransform.Rotate (Vector3.down * speed * Time.deltaTime);
}
}
Isn't there a shorter way? Am I doing something wrong?
Your answer
Follow this Question
Related Questions
How to get "on trigger enter"( or exit) to only react to a specific tag 1 Answer
how to separate differents triggers 1 Answer
Instantiate a canvas with a button when trigger 0 Answers
clicking button using script? 1 Answer
[resolved] How do I deactivate a button once its height is < 40 in c# 0 Answers