On my latest game project, I designed a new interaction system. To make my character able to interact with the environment, I use a system based on mainly three classes.
– AAction (with some ADecorator)
This script is attached to the character, it manage the interaction and the different suitable action.
This component has a list of targets.
Derived in Act_Open, Act_Describe, etc… this script define a capability. Each action has one or more Decorator, which are basically condition in the form of a script.
This script make an object interact-able by a touch. Whenever the character will be in the trigger collisionBox of this object, it will be added in the target list of InteractionComponent.
How does it work?
We have on the level a GameObject with an Int_Touch script and a Key script.
Thanks to the Int_Touch, the Key will be added in the player’s InteractionComponent target list.
The player will then press the « use » button, which will trigger the ProximityInteraction function of the InteractionComponent script. This function will go through every action the character is capable of, and try each of them.
In this case, the character as a Act_Pickup action, attached with a decorator Dec_IsClass. For the Try to be a success, the target must have a component of the type specified by the decorator Dec_IsClass, which is here Key. The condition of the decorator being met, the action Act_Pickup is valid and will be launched.
And, voilà, the key is picked up.
I created a quick project demonstrating this system. I took several script from my main game project and simplified them. The demonstration is meant to be played in editor, and the more important part are the script. For the purpose of explanation I heavily commented the different script, so feel free to have a look.
The project is available on my github at this adress, you can either clone the entire repository or pick the script files.
To make it work, clone the repository with the Assets and ProjectSettings directory. Launch Unity3D and choose to open a project, select the directory where Assets and ProjectSettings are. And you are good to go.
Thanks for playing!