I don't know whether this solution is good or not, but here is what I did. Note that this could be simplified if you had the garantee that only one item could move at once. I do not know how viable this solution would be for a different usecase, for instance if numerous animations are expected to run very often.
I created a new Monobehavior class ItemSlotAnimatorManager
, along with a regular class ItemSlotAnimator
.
The logic for moving item images around was moved to ItemSlotAnimator
s. One of those objects can only handle one animation at a time.
The ItemSlotAnimatorManager
in the scene contains a pool of animators which it populates in Awake. For each animator it creates, it also instanciateinstanciates a copy of my Item Sprite prefab, and passes its Image component to the animator which will use it.
The inventory UI can then use the manager to request an animation to be performed.
The manager keeps two lists of animators: One for idle animators, another for animators in use. Its Update loops through animators currently in use and make callcalls their method to update them. The update method of animators returns falsetrue
when the animation is over, which allows the manager to know which animators need to be returned to the idle animator list.
The GameObject which contains the ItemSlotAnimatorManager
only needs to be placed below your inventory in your UI.
This solution will be limited by the number of animators in the pool, so this needs to be keeptkept in mind - for instance by preventing the spamming of actions that trigger the animations, having a bit more animators than you think would be reasonably necessary, and defining behavior in case no animators are available.
Notes for decisions I took:
- Handling separate lists for idle and active animators, so you do not loop through idle animators for no reason during each Update, and you can just pop an idle animator when one is needed without having to search.
- Using a pool to prevent the creation and destruction of animator objects every time an animation occurs and finishfinishes
- Maybe I could do away with the animator class and have one object handle as many animations as it wants, I have no idea if this would be more efficient, and I am not bothering.