[SOLVED]Removing gameobject from list don't change the index

I have this code:

public List<GameObject> charButtons = new List<GameObject>();
    [HideInInspector]
    public GameObject currentChar;
    [HideInInspector]
    public Text currCharText;
    private List<Text> cBT;
    private string[] buttonTexts = new string[] {"Strength 5", "Agility 5", "Intelligence 5", "Charisma 5", "Diplomacy 5" };

    public int CharButtIndex
    {
        get
        {
            return currCharIndex;
        }
        set
        {
            currCharIndex = value;
        }
    }

    private void Start()
    {
        LevelIsOver = false;
        IsNextWave = false;
        //Time.timeScale = 1;
        int size = charButtons.Count;
        cBT = new List<Text>(new Text);

        for (int i = 0; i < charButtons.Count; i++)
        {
            charButtons *= (GameObject)Instantiate(characterButtonPrefab);*

charButtons*.transform.SetParent(characterButtonContainer.transform, false);*

cBT = characterButtonPrefab.transform.FindChild(“Text”).GetComponent();
cBT*.text = buttonTexts[Random.Range(0, buttonTexts.Length)];*

int charButtonIndex = i;
charButtons*.GetComponent().onClick.AddListener(() => SelectChar(charButtonIndex));*
}

SelectChar(0);
}

// Update is called once per frame
void Update ()
{
if(LevelIsOver)
{
return;
}

if(Input.GetKeyDown(“e”))
{
EndLevel();
}

* if(PlayerStats.Lives <= 0)*
{
EndLevel();
}
* }*

public void SelectChar(int _index)
{
if (charButtons.Count > 0)
{
if(currentChar != null)
{
Destroy(currentChar);
}

//Debug.Log("Index is: " + _index);
currentChar = (GameObject)Instantiate(charButtons[_index]);
CharButtIndex = _index;
Debug.Log("Property index is: " + CharButtIndex);

currentChar.transform.SetParent(optionsContainer.transform, false);
currentChar.transform.SetSiblingIndex(0);
currentChar.GetComponent().onClick.AddListener(() => CharacterSelection());

charSelectionUI.SetActive(false);
}
}

public void RemoveAndDestroyButton(int _index)
{
Destroy(charButtons[_index]);
charButtons.RemoveAt(_index);
cBT.RemoveAt(_index);
SelectChar(0);
}
The list get resized but when I try to select a new char instead of index is selecting index + 1. If I remove another object is selecting index + 2 and so on

Two things that may help:

Your loop is going through too many iterations.

Your count will start at 1, but the index starts at 0.
So if you have 10 items, the index will be 9.

Amend your loop to this:

for (int i = 0; i < (charButtons.Count-1); i++)

Secondly, you only seem to be setting the listeners at the beginning. The fifth item (index 4) will remain index 4 even when you delete items. If you delete item 3, button number 3 will activate 4. Do it again and button 2 will activate 4.

So you’d need to also remove all the listeners and recreate them after you’ve resized the list.

I hope that makes sense?