Programmatically determining number of abilities

I didn’t love the serialized field in PlayerController for number of abilities. So I dynamically computed it based on the number of slots we actually have. This eliminates needing to keep these two things in sync. It turned out to be not as easy as I hoped but it was simple enough. Here are the modifications you need to do.

public class PlayerController : MonoBehaviour
{
     private int numberOfAbilities;

     private void OnEnable()
        {
            actionStore.storeUpdated += ActionStore_storeUpdated;
        }
        
        private void OnDisable()
        {
            actionStore.storeUpdated -= ActionStore_storeUpdated;
        }

        private void ActionStore_storeUpdated()
        {
            numberOfAbilities = actionStore.GetDockedItemSlotCount();
        }
}
public class ActionStore : MonoBehaviour, ISaveable
{
        /// <summary>
        /// How many docked item slots are potentially in use? Technically this only looks as far as the last slot
        /// currently in use. If there are 6 slots and slot indices 0 and 3 are used, this will return 4.
        /// This is because we know at least slots 0,1,2,3 (4 total) are available for a user to select.
        /// This returns 0 if no slots are in use.  
        /// </summary>
        /// <returns>The number of docked item slots that can be used</returns>
        public int GetDockedItemSlotCount()
        {
            int maxSlotIndex = -1;
            foreach (int key in dockedItems.Keys)
            {
                if (key > maxSlotIndex) maxSlotIndex = key;
            }
            return maxSlotIndex + 1;
        }
}

Privacy & Terms