Adding & Removing Elements
9_ScriptableDictionaries
To add an entry into a scriptable dictionary is the same as adding an entry in a regular dictionary.
In this example, each element prefab has a component "AddRemoveElementToDictionary" attached to it. Navigate to the hierarchy and select one element template object (you can choose any element, but I will show Water):

Now, look in the inspector to check out its components:

The nice part about using a Dictionary, is that we can have different cases when the item is already in the dictionary or not. Here is how an entry is added or removed:
private void Start()
{
_element = GetComponent<Element>();
//Try to add the first element of this type
if (!_scriptableDictionary.TryAdd(_element.ElementType, 1))
{
//If its already in, just increment the count
_scriptableDictionary[_element.ElementType]++;
}
}
private void OnDestroy()
{
//Decrement the count of the element
_scriptableDictionary[_element.ElementType]--;
//If the count is 0, remove the element from the dictionary
if (_scriptableDictionary[_element.ElementType] == 0)
{
_scriptableDictionary.Remove(_element.ElementType);
}
}
Last updated