Action List
| actionlist.cs | |
| File Size: | 8 kb |
| File Type: | cs |
The Action List is a system that utilizes the command pattern to allow scripts the ability to interpolate Unity GameObjects in a single line of code. While other commercial engines often have a similar function built-in, Unity 6 is still missing this incredibly helpful system. Below is my implementation of an Action List along with an in-depth description of how it works.
List Implementation
First bit of code is the List itself, and there isn't much that's happening here. It's meant to run through the list and update each action every frame. the Update() call returns a Boolean signifying whether the action has finished or not. You'll note that I have two lists. One is to store all the actions in the action list, while the other is a buffer to allow actions to be added while iterating through the list. Another interesting feature of this list is how it removes actions. Since actions can last for a varying length of time, we may end up having to remove actions seemingly randomly throughout the list. By doing in place compacting on the list while iterating through it, we avoid potentially expensive repeated calls to currentActions.Remove() which has an O(n) time complexity per call.
Interpolation Functions
Interpolation functions for reference. Most of the math is grabbed from easings.net and translated into C#.
Abstract Action Class
Next we have the action. Or rather, the base class for the actions. Lot's of things happening here, but first, lets note that this is an abstract class. Meaning that it needs to be inherited from before it can be instantiated. While this does go against the common adage to prefer 'composition over inheritance' I want to go into some of the reasons why I chose to use it here. One of the bigger reasons to prefer composition is that it will often reduce complexity in the long run, but in this case, the nature of this system guarantees that it is small enough and simple enough where we'll never need to want to inherit more than one class. If we wanted to expand the scope of what we could do with the action list however, then it might be worth considering using composition. One possible consideration if I were to rewrite the action list using composition might be to separate the delay from the interpolation, as I do use actions that utilize the delay, but not the interpolation (See Example: Callback Function).
Example: Move Action
Here is an example implementation of that abstract action class that moves 2D game objects in Unity. We grab our start position the before the first time the Action will Act and do any one time calculations. After that, the Act() Function is a simple one line function.
Example: Callback Action
Lastly, here is a Callback Action. All it does is wait for a delay, and then calls the callback function.