Search Unity

Controlling a Slider

Discussion in 'Scripting' started by agpardo, Dec 9, 2018.

  1. agpardo

    agpardo

    Joined:
    Jul 17, 2018
    Posts:
    4
    Hi all,
    I am developping a videogame, where the player needs to assign some points into several skills (Speed, Force, Precision, Jump).

    This is done in a menu, that contains a TMP_Text with the remaining points that user can assign, and 4 different Sliders, to control the number of points assigned to each skill.

    My idea was that once the user has assigned all the points, disable all the sliders (I can do that: slider.enable=false). But, the user could reduce the number of points in a categorty, and then he will have more points to spend in the rest of skills. So, what I need is when the user has assigned all the points, allow user to reduce the number of points, but not increase it.

    I give you an example: I have 7 points to assigned, and I put 3 points to Speed; 2 to Force, and 2 to Precision. So, I ran out of points.

    How can I allow the user to reduce the points assigned to Speed, Force, or Precision, but not allow him to assign more...

    I do not know if it makes sense.

    In this example that I have explained, the user can reduce Speed, Force or Precision... but he can not increase any of these values, because (with this configuration) he does not have more points....
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Code (CSharp):
    1.     public bool disableAdd;
    2.     public Slider slider;
    3.     float newValue;
    4.  
    5.     private void Start()
    6.     {
    7.         newValue = slider.value;
    8.     }
    9.     public void CheckIfCanAdd()
    10.     {
    11.         if(disableAdd)
    12.         {
    13.             if(slider.value > newValue)
    14.             {
    15.                 slider.value = newValue;
    16.             }
    17.         }
    18.  
    19.         newValue = slider.value;
    20.     }
    21.  
    You'll want to tie the method into the OnValueChange event on the slider. Then when you need to disable the ability to add, just loop through the sliders and set the bool to true. If they subtract a point and you have points they can add back in, loop through again and turn the bool to false.

    This was just a quick write up, so it may not be perfect, but should give you an idea. (you could combine the two if statements into 1 if you wanted also)