using System; using System.Collections.Generic; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// /// A List of type AtomBaseVariable. Used by AtomList. /// [Serializable] public class AtomBaseVariableList : List, ISerializationCallbackReceiver, IAtomList { public Action Added { get => _added; set => _added = value; } public Action Removed { get => _removed; set => _removed = value; } public Action Cleared { get => _cleared; set => _cleared = value; } private event Action _added; private event Action _removed; private event Action _cleared; [SerializeField] private List _serializedList = new List(); public void OnAfterDeserialize() { if (_serializedList != null) { base.Clear(); for (var i = 0; i < _serializedList.Count; ++i) { base.Add(_serializedList[i]); } } } public void OnBeforeSerialize() { _serializedList.Clear(); for (var i = 0; i < this.Count; ++i) { _serializedList.Add(this[i]); } } /// /// Generic getter. /// /// The index you want to retrieve. /// The expected type of the value you want to retrieve. /// The value of type T at specified index. public T Get(int index) where T : AtomBaseVariable { return (T)this[index]; } /// /// Generic getter. /// /// The index you want to retrieve. /// The expected type of the value you want to retrieve. /// The value of type T at specified index. public T Get(AtomBaseVariable index) where T : AtomBaseVariable { if (index == null) throw new ArgumentNullException("index"); return (T)this[index.Value]; } /// /// Add an item to the list. /// /// The item to add. public new void Add(AtomBaseVariable item) { base.Add(item); _serializedList.Add(item); Added?.Invoke(item); } /// /// Remove an item from the list. /// /// The item to remove. /// True if it was removed, otherwise false.. public new bool Remove(AtomBaseVariable item) { var removed = base.Remove(item); _serializedList.Remove(item); if (!removed) return false; Removed?.Invoke(item); return true; } /// /// Remove an item at provided index. /// /// The index to remove item at. public new void RemoveAt(int index) { var item = this[index]; base.RemoveAt(index); _serializedList.RemoveAt(index); Removed?.Invoke(item); } /// /// Insert item at index. /// /// Index to insert item at. /// Item to insert. public new void Insert(int index, AtomBaseVariable item) { this.Insert(index, item); _serializedList.Insert(index, item); Added?.Invoke(item); } /// /// Ckear list. /// public new void Clear() { base.Clear(); _serializedList.Clear(); _cleared?.Invoke(); } } }