So I have a list in my Unity project, and when I remove one element from that list during play mode, for example from the first slot, the list is shrinking. I want to make that list to stay the same size as before, but I don’t know how. Is there a way to for example, replace the removed object with a null object?
Also, here’s that part of the code I’m talking about now:
public class Inventory : MonoBehaviour
{
public List<GameObject> items;
public GameObject selectedGameObject;
public int SelectedItem = 0;
public int maxSlots;
public int maxStack;
public ItemSlot[] itemSlot;
public void AddItem(string itemName, int quantity, Sprite itemSprite, string ItemDesc, GameObject itemObj)
{
for (int i = 0; i < itemSlot.Length; i++)
{
if (itemSlot[i].IsFull == false)
{
itemSlot[i].AddItem(itemName, quantity, itemSprite, ItemDesc);
items.Add(itemObj);
selectedGameObject = itemObj;
UpdateSelectedItem();
return;
}
}
SelectedItem = items.IndexOf(itemObj.gameObject);
}
public void RemoveItem(GameObject itemObj)
{
for (int i = 0; i < itemSlot.Length; i++)
{
itemSlot[i].RemoveObj();
items.Remove(itemObj);
}
}
}
I want to make a system that will allow me to remove object from a list without shrinking it whenever I call the RemoveItem().
The list of the objects is shrinking whenever I try to remove one element from there. I want that list to stay the same size, so even if the object gets removed the list size stays the same.
>Solution :
Get the index of the object you want to remove from the list and set it to null.
int index = items.IndexOf(itemObj);
if (index != -1) {
items[index] = null;
}
Therefore, the modified RemoveItem() method would be:
public void RemoveItem(GameObject itemObj)
{
for (int i = 0; i < itemSlot.Length; i++)
{
itemSlot[i].RemoveObj();
}
int index = items.IndexOf(itemObj);
if (index != -1) {
items[index] = null;
}
}
In the above method, I moved the code that removes an object from the list outside the for loop, because it doesn’t make sense to keep removing the same item multiple times from the list, which just adds load to the execution.