# Unity 4.6 UI Replace Images on selection in List of buttons[i]

I made a list containing all the buttons in the UISelectionCanvas and would like to change each image as it is being selected. The problem is once the selection selects a new type of unit it will change all the buttons sprites in the list to the new selection instead of just changing the one selected.

     for a example imagine I have 10 units 9 peasants and 1 warrior


as each peasant is selected the sprite adds the peasant icon to the button. if 8 peasants are selected and then the 9th selection is a warrior it changes all 9 buttons to a warrior icon then if I selects the 10th peasant it changes them all back to peasant.

        for (int i = 0; i < buttons.Count; i++)
{
for (int c = 0; c < SelectedUnits.Count; c++)
{
if (i <= c)
{
buttons[i].SetActive(true);

foreach (var unit in SelectedUnits)
{
if(unit.tag == "Peasant")
{
buttons[i].transform.GetComponent<Image>().sprite = peasant as Sprite;
}
else if(unit.tag == "CityGuard")
{
buttons[i].transform.GetComponent<Image>().sprite = warrior as Sprite;

}
}

}
else
{
buttons[i].gameObject.SetActive(false);
}
}


}

• You should really clean up the indenting of the brackets around code blocks, so that you can more easily see where each code block begins and ends; right now I keep getting confused about which else statement goes with which if. – jhocking Jan 15 '15 at 19:24

You probably don't want to be looping through SelectedUnits (not at all, and definitely not twice!) So something like:

for (int i = 0; i < buttons.Count; i++) {
if (i < SelectedUnits.Count) {
buttons[i].SetActive(true);
var unit = SelectedUnits[i];

if(unit.tag == "Peasant") {
buttons[i].GetComponent<Image>().sprite = peasant as Sprite;
}
else if(unit.tag == "CityGuard") {
buttons[i].GetComponent<Image>().sprite = warrior as Sprite;
}
}
else {
buttons[i].SetActive(false);
}
}

• Awesome jhocking thanks I am not sure how I let that piece get so out of hand it works perfectly. – Justin Markwell Jan 15 '15 at 19:58