.NET 4.5 has ObservableCollection in System.Collections.ObjectModel.ObservableCollections
It allows notifying when elements are added or removed from the collection.
I’m wondering what could I use in Unity, since its Mono is equivalent to .NET 4.
I could do the obvious, create my own class with indexer that looks like, say, an array, and manually send notifications. But I was wondering if there’s anything already built before I re-invent the array (or another collection for that matter).
Well you could use this script, I don’t believe you can access the built in .NET 4 ones:
[Serializable]
public class ObservedList<T> : List<T>
{
public event Action<int> Changed = delegate { };
public event Action Updated = delegate { };
public new void Add(T item)
{
base.Add(item);
Updated();
}
public new void Remove(T item)
{
base.Remove(item);
Updated();
}
public new void AddRange(IEnumerable<T> collection)
{
base.AddRange(collection);
Updated();
}
public new void RemoveRange(int index, int count)
{
base.RemoveRange(index, count);
Updated();
}
public new void Clear()
{
base.Clear();
Updated();
}
public new void Insert(int index, T item)
{
base.Insert(index, item);
Updated();
}
public new void InsertRange(int index, IEnumerable<T> collection)
{
base.InsertRange(index, collection);
Updated();
}
public new void RemoveAll(Predicate<T> match)
{
base.RemoveAll(match);
Updated();
}
public new T this[int index]
{
get
{
return base[index];
}
set
{
base[index] = value;
Changed(index);
}
}
}