Hello,
I am creating a gallery where you can add and remove elements. I am using three buttons, one to add the elements (button), another to see the elements (button) and the last one is to remove the button from that element (button).
When I add a number of buttons and then delete a randomly selected one, it is deleted (the button and the reference in the list are destroyed) but if I try to eliminate the last button, it throws an index error out of range
This is my code:
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class CreateList : MonoBehaviour
{
public GameObject _buttonPrefab;
[HideInInspector]
public Button _delete;
public RectTransform _contentGallery;
public List<GameObject> _buttonFileList = new List<GameObject>();
public int _index;
public int _currentGallery;
private void Start()
{
_index = 0;
}
public void AddButtonList()
{
int tempIndex = _index;
GameObject _spamButton = (GameObject)Instantiate(_buttonPrefab);
Button _btnPlay = _spamButton.GetComponent<Button>();
_spamButton.name = "Button" + "_" + (_index);
_btnPlay.onClick.AddListener(() => ClikButtonList(tempIndex));
TextMeshProUGUI var = _spamButton.GetComponentInChildren<TextMeshProUGUI>();
var.text = "Button_" + _index.ToString();
_delete = GameObject.Find("ButtonPrefabDelete").GetComponent<Button>();
_delete.name = "Delete" + "_" + (_index);
_delete.onClick.AddListener(() => DeleteButtonList(tempIndex));
Debug.Log("tempIndex vale: " + _index);
_spamButton.transform.SetParent(_contentGallery, false);
_spamButton.transform.localScale = new Vector3(1, 1, 1);
_buttonFileList.Add(_spamButton);
_index += 1;
}
public void ClikButtonList(int index)
{
Debug.Log(index);
}
public void DeleteButtonList(int index)
{
Debug.Log(index);
Destroy(_buttonFileList[index]);
_buttonFileList.RemoveAt(index);
}
}
I am doing something wrong?
Edit1: I add the package of my project, I am using unity 2019
Link: Gallery package
Edit2: If I add four elements in the list they would be from 0 to 3, if I eliminate the element 1 it is eliminated and the list is traversed, but if I eliminate the last value of the new list, element 2 gives me an error of value out of list range.