ObservedSet

ObservedSet is a generic class that extends the ISet<T> interface and provides change notifications when items are added, removed, or when the set is cleared.

A set is a collection of items that are distinct from one another, meaning that no two items in the set are the same. Sets are useful for storing and manipulating collections of data where each item is unique and does not need to be repeated.

Sets can be useful in game development for a variety of purposes. Some examples include:

  • Storing unique items in an inventory system

  • Keeping track of unique objects in a scene

  • Checking if a player has already visited a specific location

  • Checking if a player has already collected a specific item

By using a set, you can ensure that no duplicates are added, which can make it easier to keep track of data and avoid potential bugs. The ObservedSet class provided in this package allows you to subscribe to changes made to the set, allowing you to react to those changes in your game.

Usage

Create an ObservedSet:

ObservedSet<int> set = new ObservedSet<int>();

You can then add items to the set using the Add method:

set.Add(5);
set.Add(10);

To subscribe to changes in the set, use the Subscribe method and pass in a callback function:

set.Subscribe((item, changeType) => {
    Debug.Log($"Item {item} was {changeType}");
});

Now, whenever an item is added or removed from the set, the callback function will be called and the change type (either Added or Removed) will be printed to the console.

You can also use the Unsubscribe method to stop receiving notifications:

set.Unsubscribe((item, changeType) => {
    Console.WriteLine($"Item {item} was {changeType}");
});

Finally, you can use all of the other methods and properties of the ObservedSet just like you would with a regular HashSet. For example:

// Check if set contains an item
bool containsFive = set.Contains(5);

// Remove an item from the set
set.Remove(5

Last updated