How to lock slider increase?
I have two sliders. and what I want to happen is that when value of both of the sliders is equal to 50 then I want player to not be able to increase slider value further, however still be able to decrease the value. another thing I think I would have to do is to make one of slider value decrease to 50 when value of both sliders is higher than 50.
public class SliderLock : MonoBehaviour
{
public Slider AssasinLock;
public Slider DestroyerLock;
public float LockNumber = 50;
public float sum;
// use this initialization
void Start()
{
}
// Update is called once per frame
public void Update()
{
sum = AssasinLock.value + DestroyerLock.value;
if(LockNumber <= sum)
{
DestroyerLock.interactable = false;
AssasinLock.interactable = false;
}
else
{
DestroyerLock.interactable = true;
AssasinLock.interactable = true;
}
}
}
Answer by streeetwalker · Jun 28, 2020 at 06:21 PM
@nedan, don't do it in your update loop - it is inefficient to waste update cycles on that. The below uses Unity Events on the sliders components, which are only called when the slider changes.
That said, This is kind of a long way around, and not the most efficient code, but it works.
The basic idea is to keep a separate max value for each slider, and adjust them upward or downward when the other slider is moved.
The following can be dropped on any game object, and then plug in the sliders to the inspector fields. The other two variables can be made private, but are there for you to watch the max values for each slider if you like.
The code assumes you are working with integer values (check the slider to use Whole Numbers checkbox), and you've set the maximums to 100 for each slider.
Then set up a Unity Event on each slider, drop the game object that owns the below script on Event object field, and then choose the appropriate Dynamic Float function name (e.g. SetSlider1Value ) from the function drop down in the Unity event for each slider.
public class SetSliders : MonoBehaviour
{
public Slider slider1;
public Slider slider2;
public int totalValue = 100;
public int[] sliderMaxes;
public void Start() {
sliderMaxes = new int[]{ 100, 100};
}
public void SetSlider1Value( System.Single currentValue ) {
LimitSlider( slider1, currentValue, 1, 2 );
}
public void SetSlider2Value( System.Single currentValue) {
LimitSlider( slider2, currentValue, 2, 1 );
}
public void LimitSlider( Slider aSlider, float currentValue, int thisIndex, int otherIndex ) {
int current = Mathf.CeilToInt( currentValue );
if( current > sliderMaxes[thisIndex - 1] ) aSlider.value = sliderMaxes[thisIndex - 1];
sliderMaxes[otherIndex - 1] = totalValue - current;
}
Your answer
Follow this Question
Related Questions
How to make or find advanced UI assets 1 Answer
link GUI slider to shader opacity 0 Answers
Make 2 sliders dependent on each other 1 Answer
Slider isn't moving smoothly. (Unity3d) 1 Answer
Does anyone know why this script has a strange icon? 1 Answer