- Home /
Triple Slider control - UI slider value control
I am in a bit of a pickle, and I am trying to solve it in the best way possible. I am trying to achieve that the 3 sliders are all summing up to 1 in total, and if one slider is shifted, then the other ones will adjust proportionally. I have the following script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class TripleSliderAdjustment : MonoBehaviour {
private Slider primaryslider;
public Slider sliderB;
public Slider sliderC;
private void Start()
{
primaryslider = GetComponent<Slider>();
}
public void UpdateSliders()
{
float sliderCValue = ((1 - primaryslider.value) / (sliderB.value + sliderC.value)) * sliderC.value;
float sliderBValue = ((1 - primaryslider.value) / (sliderB.value + sliderC.value)) * sliderB.value;
sliderC.value = sliderCValue;
sliderB.value = sliderBValue;
}
}
This script is attached to each sliders, and SliderB and SliderC is both manually placed. However, the problem arise when I move one slider, then the other sliders are also updated, and there is somewhat of a performance issue, as all 3 are then updated, and all 3 will then attempt to update.. and there is a "semi infinite loop" going on (it will eventually stop.. but will go on for a while) Does anyone have a suggestion on how this could be solved - as I am going completely blind on this topic :) If I find the answer myself, I will post it here.
Answer by hexagonius · Mar 27, 2018 at 05:27 PM
each slider should have an value changed event. if you register the update sliders method to all of them you just need to iterate then once, skip the one which already has the correct value and recalculate the others.
I am not sure I completely understand what you are saying here - but you are telling me that I should only focus on the one slider I am moving, and then update the other two? So, this is the problem in a nutshell, I do not know which one have the correct value (or in fact, all 3 of them have the correct value at all time) So what I need to know is - which one slider am I moving? Is there any neat trick to seeing which one is manually changed and which ones are changed through scripts? If I update Slider A - then Slider B and Slider C will both be updated - each of them will now update the two others ones -- and so on :)
the value changed event should also return the changed value. comparing that and you'll know which one it was that changed.
Of course, since all sliders would call the same method you'd need be remember the ones you're adjusting and skip their callback during your updating loop.