1

Hello I would like to add a slider to my unity3d project, I am using c# script and the following code.

 public float hSbarValue;
 void OnGUI() {
         hSbarValue = GUI.HorizontalScrollbar(new Rect(25, 25, 100, 30), hSbarValue, 1.0F, 0.0F, 100.0F);
    }

This draws a slider that i have to use the mouse to drag it.

I want to turn it into a slider that moves on its own (like ping pong effect) until a button is pressed and then store the value in the hSbarValue variable.

Any help is appreciated

2 Answers 2

1

You might try using a Coroutine to increase the value of it and kill the coroutine when the button is pressed. Something like:

IEnumerator IncrementValue() {
    while (true) { // Or a better limit
        hSbarValue += someIncrementValue;
        yield return new WaitForSeconds(1); // Or other value
    }
}

void Start {
    StartCoroutine("IncrementValue");
}

// later inside the button press handler
StopCoroutine("IncrementValue");
Sign up to request clarification or add additional context in comments.

2 Comments

Works for me. One note, the op mentioned something about a "ping pong" effect, your coroutine only ever increments so the slider never goes back to 0. (I'm assuming ping pong means back and forth)
@jerdak I didn't write code for him to use directly, obviously it would be necessary to modify it for his needs, in the case of a ping pong effect he'd need to check if it needed to be incremented or decremented. He can pay me to write exactly what he needs :P
1

hSbarValue = GUI.HorizontalScrollbar(new Rect(25, 25, 100, 30), Mathf.PingPong(Time.time*5.0f, 20), 1.0F, 0.0F, 50.0F);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.