Since there is no support for serializing ObservableCollection
of C# in Unity as of yet, I am using a script which extends List<>
and creates a Serializable class called ObservableList
as mentioned in this unity forum answer ObservableList. Following is the same code:
[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);
}
}
}
Still it is not being serialized and I cannot see it in Unity editor. Any help would be greatly appreciated!
EDIT #1
Intended Use case:
public class Initialize : MonoBehaviour
{
public ObservedList<int> percentageSlider = new ObservedList<int>();
void Start()
{
percentageSlider.Changed += ValueUpdateHandler;
}
void Update()
{
}
private void ValueUpdateHandler(int index)
{
// Some index specific action
Debug.Log($"{index} was updated");
}
}
I am attaching this script as a component to a GameObject so that I can input the size
of this list, play around with the values (just like I can do with List
) and perform some action which only gets fired when some value inside the ObservableList
is updated.
What I want to see
What I am seeing