Why this fuction make the game to pick numbers which is already removed from list through Random.Range?

void AvailableMoves()
{
for (int i = 0; i < buttonList.Length; i++)
{
if (buttonList*.text == “”)*
{
availableList.Add(i);
}
else
{
availableList.Remove(i);
}
availableMin = availableList.Min();
availableMax = availableList.Max();
availableRandom = availableList[Random.Range(availableMin, availableMax)];
}
}
It’s a Tic-Tac-Toe game with AI.
When it’s its turn, before it plays, this function will check every button if it’s unoccupied then it will be added in a list of available buttons. If not, it will be removed.
But AI can still pick buttons which is already removed.
Why? Thanks.

If you have only 2 unoccupied buttons (ex : 1 and 7), Min() will evaluate to 1, Max() will evaluate to 7, Random.Range(availableMin, availableMax) will return any number between 1 and 7, it may return 2,3,4,5 or 6 which are in range but are occupied.

The correct way is something like this:

void AvailableMoves()
    {
        // Resetting the list as .Clear() will clear values but keep the capacity of the list
        availableList = new List<int>();
        for (int i = 0; i < buttonList.Length; i++)
        {
            if (buttonList*.text == "")*

{
// Adding only unoccupied buttons
availableList.Add(i);
}
}

// Checking if the list was populated
if (availableList.Count > 0)
{
availableMin = 0;
availableMax = availableList.Count;
availableRandom = availableList[Random.Range(availableMin, availableMax)];
}
else
{
// No buttons available.
}
}

Edit: code correction

@unity_k5jZb8tvx_RtNA Thanks for your explanation but I tried with that like what you said:

private List<int> availableList = new List<int>();
private int availableMin = 0;
private int availableRandom;

void AvailableMoves()
{
    for (int i = 0; i < buttonList.Length; i++)
    {
        if (buttonList*.text == "")*

{
availableList.Add(i);
}
if (availableList != null)
{
availableRandom = availableList[Random.Range(availableMin, availableList.Count)];
}
else
{
}
}
Then the console signals an error:
“ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.”