ObservedSortedSet

ObservedSortedSet<T> is a sorted set data structure that allows you to subscribe to changes made to the set. It inherits from SortedSet<T>, so it has all the same functionality as a regular sorted set, but it also has the ability to notify subscribers of changes made to the set through the Subscribe and Unsubscribe methods.

A sorted set is a collection of items that are stored in a specific order, based on their value. Sorted sets are useful for scenarios where you need to store items in a specific order and quickly retrieve items based on their value.

A set is a collection of items that are unordered and do not contain duplicate elements. Sets are useful for game development because they allow you to quickly check if an element is present in the set, add or remove elements from the set, and perform set operations such as union, intersection, and difference. For example, you could use a set to store the unique items a player has collected in a game, or to keep track of the unique enemies that have been spawned in a level.

For example, in a game where you need to keep track of high scores, a sorted set could be used to store the scores in order from highest to lowest.

Usage

Create an instance of ObservedSortedSet<T> like this:

ObservedSortedSet<int> sortedSet = new ObservedSortedSet<int>();

You can then use the Subscribe method to register a callback that will be invoked whenever an item is added or removed from the set:

sortedSet.Subscribe((item, changeType) =>
{
    if (changeType == ChangeType.Added)
    {
        Debug.Log($"{item} was added to the set");
    }
    else if (changeType == ChangeType.Removed)
    {
        Debug.Log($"{item} was removed from the set");
    }
});

You can then use all the usual methods of a SortedSet<T>, such as Add, Remove, and Clear, and the subscribers will be notified of the changes.

Action<int, ChangeType> callback = (item, changeType) =>
{
    if (changeType == ChangeType.Added)
    {
        Debug.Log($"{item} was added to the set");
    }
    else if (changeType == ChangeType.Removed)
    {
        Debug.Log($"{item} was removed from the set");
    }
};

sortedSet.Subscribe(callback);
sortedSet.Unsubscribe(callback);

You can also use the ClearSubscriptions method to remove all subscribers:

sortedSet.ClearSubscriptions();

Last updated