0
votes

I've been trying to change a button prefab's color untill another button prefab is clicked on, but if I select the last element, then delete it, I get an Argument Out Of Range Exception.

I tried to fix it by checking if the previousID is not bigger than the prefabList.Count. But it doesn't work.

Am I missing something?

the code:

public void SetColor(List<GameObject> prefabList, int ID)
{
    if (prefabList.Count != 0)
    {
        if (previousID != ID && prefabList.Count >= previousID)
        {
            Debug.Log("ID: " + ID + "previous ID: " + previousID);
            prefabList[previousID].GetComponent<Image>().color = Color.white;
            previousID = ID;
        }
        else if (ID == previousID)
        {
            prefabList[ID].GetComponent<Image>().color = Color.yellow;
        }            
    }        
}

Edit based on answers:

public void SetUnderEditJudgeLineColor(List<GameObject> prefabList, int ID)
{
    if (prefabList.Count != 0)
    {
        if (previousID != ID && prefabList.Count > previousID)
        {
            Debug.Log("ID: " + ID + "previous ID: " + previousID);
            prefabList[previousID].GetComponent<Image>().color = Color.white;
            previousID = ID;
        }
        else if (ID == previousID)
        {
            prefabList[ID].GetComponent<Image>().color = Color.yellow;
        }
    }        
}

Sadly, I still get the same error.

1

1 Answers

1
votes

prefabList.Count >= previousID should be prefabList.Count > previousID. The last index is always List.Count - 1 (because indexes start at 0) so, if the index and count are equal, you're checking past the end of the list.

EDIT:

You're else if statement isn't protecting from prefabList.Count so that'll also need a check against the size of the list:

else if (ID == previousID && ID < prefabList.Count)