- Home /
Question by
Gabimela · Mar 18, 2021 at 03:48 PM ·
c#uiunity 2dvisual studiouser interface
Change image in UI depending on the value of the slider
I am trying to make the images change in the UI when the slider's value is changed, right now nothing is happening when i move the slider, this is my code:
public class ImagesSlider : MonoBehaviour
{
// Start is called before the first frame update
public Sprite sprite1;
public Sprite sprite2;
public Sprite sprite3;
public Sprite sprite4;
public Sprite sprite5;
public Sprite sprite6;
public Sprite sprite7;
public Sprite sprite8;
public Sprite sprite9;
public Sprite sprite10;
public Sprite sprite11;
public Slider imageslider;
void Start()
{
gameObject.GetComponent<Image>();
}
void Update()
{
ChangeImage();
}
// Update is called once per frame
void ChangeImage()
{
if (imageslider.value == 1.0f)
{
gameObject.GetComponent<Image>().sprite = sprite1;
}
if (imageslider.value == 2.0f)
{
gameObject.GetComponent<Image>().sprite = sprite2;
}
}
Comment
Do you have any error in the console at runtime (a NullReferenceException for instance)
Is your slider using whole values?
What does
Debug.Log(imageslider)
inChangeImage
output?
I would recommend doing something like this (code not tested):
public class ImagesSlider : MonoBehaviour
{
public Sprite[] sprites;
public Slider slider;
public Image image;
void Start()
{
slider.onValueChanged.addListener(ChangeImage);
}
void ChangeImage(float value)
{
int intValue = Mathf.FloorToInt(value);
if (intValue >= 0 && intValue < sprites.Length)
image.sprite = sprites[intValue];
}
}
Your answer
Follow this Question
Related Questions
Next Scene not loading after all enemies are destoryed 0 Answers
If player runs out of time and does not kill the required enemies go to the lose scene 1 Answer
Collider trouble 0 Answers
Why does my character only rotate once when it stops moving? 0 Answers
Does anybody know how to fix (repositories.cfg could not be loaded) problem? 3 Answers