OnChange in List

Hi there!

I wondering there has any event to fire or trigger when the List variable has something changed?

if I have
List Items = new List();
like this

how to simply know if it has changed?

Thanks!

C# Does not raise events on items changed.

I ran your question through ChatGPT and it gave me an Obervable List for you to try.

using System;
using System.Collections.Generic;
using UnityEngine;

public class ObservableList<T>
{
    private List<T> _items = new List<T>();

    public event Action ListChanged;

    public void Add(T item)
    {
        _items.Add(item);
        ListChanged?.Invoke();
    }

    public void Remove(T item)
    {
        if (_items.Remove(item))
        {
            ListChanged?.Invoke();
        }
    }

    public int Count => _items.Count;

    public T this[int index]
    {
        get => _items[index];
        set
        {
            _items[index] = value;
            ListChanged?.Invoke();
        }
    }

    public void Clear()
    {
        _items.Clear();
        ListChanged?.Invoke();
    }
}

public class Item
{
    // Item properties and methods
}

public class TestObservableList : MonoBehaviour
{
    private ObservableList<Item> observableList;

    void Start()
    {
        observableList = new ObservableList<Item>();
        observableList.ListChanged += OnListChanged;

        var item1 = new Item();
        var item2 = new Item();

        observableList.Add(item1); // Output: List changed!
        observableList.Add(item2); // Output: List changed!
        observableList.Remove(item1); // Output: List changed!
        observableList.Clear(); // Output: List changed!
    }

    private void OnListChanged()
    {
        Debug.Log("List changed!");
    }
}

You don’t need a Custom Item, you can pass through a string and such.

1 Like

Thank you for your anser!
we can’t use theList.GetHashCode() to check if it has changed?

Why would you? GetHashCode is used in comparisons/lookups (such as with dictionaries). It’s not really meant to be used for knowing when something has changed. That’s what delegates are for.

1 Like

I just want to make an inventory system to collect Items in List
and I just want to know those Items has something change or not

It’s your list. So every time you add or remove an item, you know and can inform any other script interested in this change.

Of course this requires encapsulating the List. Do not simply create “public List Inventory” and let any other script freely modify that List.

Instead like the Observable example above, any such collection ought to be its own class. Basically your non-generic InventoryItemList where you override just the needed Add and Remove methods, and add two Actions to observe adds and removes.

2 Likes