- Home /
Change slider color to green when value is 50
Hello. I am making a slider that should change it's value based on the specified spot when the handle gets near. Currently my script is only able to do this either on the left or right side (0 or 100). How do I need to change it?
This is the line responsible for color updating: sliderFill.color = Color.Lerp(Color.red, Color.green, slider.value / 100);
I want the color green to start showing up when the handle is nearing the specified position (which at first is 50/100, but will later be randomized).
Answer by swanne · May 09 at 03:07 PM
Hey,
You could substitute slider.value for a float variable
float target;
target = slider.value/100;
sliderFill.color = Color.Lerp(Color.red, Color.green, target);
For the random bit you could generate this float variable via function that returns a random float value.
void MyFunction()
{
float _target = RandomFunction();
sliderFill.color = Color.Lerp(Color.red, Color.green, _target);
}
float RandomFunction()
{
float _randomTarget = Random.Range(10,90);
return _randomTarget;
}
This may not be the perfect answer but hopefully it will give you an option to try and look into?
As far as I understand this code it does the same as it is currently? I wanted to find out how do I get the Lerp/gradient whatever to change to green when it gets near the specified spot. I know how to get the random value etc so no issue there. Sorry if my question was unclear!
Answer by Hellium · May 09 at 05:38 PM
You could also take advantage of the Gradient
class:
Gradient gradient;
void Start()
{
gradient = new Gradient();
// Populate the color keys at the relative time 0 and 1 (0 and 100%)
GradientColorKey[] colorKey = new GradientColorKey[3];
colorKey[0].color = Color.red;
colorKey[0].time = 0.0f;
colorKey[1].color = Color.green;
colorKey[1].time = Random.value;
colorKey[2].color = Color.red;
colorKey[2].time = 1.0f;
// Populate the alpha keys at relative time 0 and 1 (0 and 100%)
GradientAlphaKey[] alphaKey = new GradientAlphaKey[3];
alphaKey[0].alpha = 1.0f;
alphaKey[0].time = 0.0f;
alphaKey[1].alpha = 1.0f;
alphaKey[1].time = 0.5f;
alphaKey[2].alpha = 1.0f;
alphaKey[2].time = 1.0f;
gradient.SetKeys(colorKey, alphaKey);
}
public void SetHandleColor()
{
sliderFill.color = gradient.Evaluate(slider.value / slider.maxValue);
}
The color unfortunately doesn't change now at all with this bit.
I made a mistake with the alpha keys, but otherwise, it works fine.
Do you call SetHandleColor
? I put the sliderFill.color
in that function for the sake of the example, because you haven't indicated where you were calling that piece of code.
It was just being assigned in update, but I changed the code so now it is being set to green when it is at the accepted area. It's not as smooth as I would like but it's good enough.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How can I loop through all colours in code? 1 Answer
Distribute terrain in zones 3 Answers