Updating UI Text of an existing element in a list.
I'm trying to make an Inventory System by myself,but I have limited knowledge as I'm still a beginner/Junior. Anyways, I'm kinda stuck with the UI part of it. Whenever I try to check for an already existing item in the list, it works but it doesn't update the text as I want to. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class InventoryUI : MonoBehaviour
{
private List<Item> items = new List<Item>();
public void AddItemToInventory(Item item)
{
bool itemExists = items.Contains(item);
if(itemExists)
{
//Item exists, just update the text so it appears to be multiple of the same
item.itemPrefab.GetComponentInChildren<TextMeshProUGUI>().text = item.amount.ToString();
}
else
{
//Item doesn't exist.
item.itemPrefab.GetComponent<Image>().sprite = item.itemIcon;
item.itemPrefab.GetComponentInChildren<TextMeshProUGUI>().text = item.amount.ToString();
Instantiate(item.itemPrefab, transform);
items.Add(item);
}
}
}
Im using ScriptableObjects for the different items who also have an amount variable. For testing purposes I created some items in the world with an OnMouseDown script that calls the AddItemToInventory(Item item) function everytime the player clicks on the item in the game. Everything works fine, it seems. The amount gets higher in the Scriptable Object whenever I click the item in the world. And the if/else also works. I used debug.log to see if it even reaches and it does. The only thing that is not working, is that it's not updating the text that holds the amount of the already existing item, so it always stays at 1(or whatever the scriptable object's value was last). I'm pretty sure its something very simple but I just can't figure it out right now.