- Home /
[Improvement] change image based on set value
Hello everybody!
I'm very much new to Unity and wrote a little script to change an image based on a set value. The script itself works fine and i'm very happy with it. Looking at the amount of code though i wondered, if there's a more efficient way to achieve what i want it to do. Any suggestions or a little push into the right direction would be great.
Thanks in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class StarsDisplayScript : MonoBehaviour
{
public Image img1;
public Image img2;
public Image img3;
int Skills;
void Start()
{
// create random number between 1-5 (note: has to be changed to set value from persistent data later)
Skills = Random.Range(1, 6);
Debug.Log("the random number is: " + Skills);
// change image (from Resources-folder) based on set value
if (Skills == 1)
{
img1.sprite = Resources.Load<Sprite>("bronze_1");
}
else if (Skills == 2)
{
img1.sprite = Resources.Load<Sprite>("bronze_2");
}
else if (Skills == 3)
{
img1.sprite = Resources.Load<Sprite>("bronze_3");
}
else if (Skills == 4)
{
img1.sprite = Resources.Load<Sprite>("bronze_4");
}
else if (Skills == 5)
{
img1.sprite = Resources.Load<Sprite>("bronze_5");
}
}
}
Comment
Best Answer
Answer by mikelortega · Apr 19, 2017 at 10:15 AM
You can do this and delete all the ifs:
img1.sprite = Resources.Load<Sprite>("bronze_" + Skills);