Make Multiple UI Sliders Function As One
What I'm trying to do is to allow the user to divide a single resource pool into into 3 groups. I wanted to use a slider for each group indicating the percentage of the total resource pool being allocated to that group. I always want the total values of the sliders to be equal to 1 (100% resource allocation). So when one is dragged down, the other 2 go up, and when one is dragged up the other 2 go down.
I've been looking at onValueChange
, but the problem I'm having is changing the slider values in the event handler results in more calls to onValueChange
which ends up in a potential infinite loop of changes.
So, before I get too deep into trying to make this work myself, I'm curious if anyone has done this or has any ideas about how to go about implementing these sliders.
Hate to be a pain but I am doing something very similar in my game right now and I'm wondering if you've happened to develop a decent system for this because the approach I've taken has made a big mess of code and still doesn't quite work properly.
Answer by Dave-Carlile · Sep 22, 2015 at 12:17 PM
Is the OnValueChanged event being generated even if the new value you're calculating is the same? I would hope it wouldn't be, but if it is just make sure you don't redo your calculations for the other sliders again if the value didn't actually change.
An example with 2 sliders...
User sets Slider A to 20%
Slider A OnValueChanged: calculate value of slider B as 80% and set value
Slider B OnValueChanged: calculate value of slider A as 20% and set value
In step 3 I would hope that Slider A wouldn't get another OnValueChanged event since the value didn't actually change even though you're setting it. But if Unity still generates the event then you can just do the compare yourself and not set the property if it's the same...
Slider B OnValueChanged calculate value of slider A as 20% if (slider A value != 20%) set value of Slider A to 20%
And you might want to use Mathf.Approximately for the comparison to avoid generating the event due to rounding errors.
Now, with 3 sliders, if OnValueChanged is executed immediately when you set the slider value then you'd still have problems since the 3rd slider value hasn't changed yet. You might need to keep separate copies of the values, calculate them all at once, then let the sliders pull their values from those.