Made With Unity | 2D Space Shooter Part 12: C# Action Delegates In Unity
Where making 3 changes in our game: 1) Add Action Delegates feature when a player dies, 2) Add our Restart function to use the New Input System and 3) change where we are getting the input.
Creating the Action
Unity Actions allow you to dynamically call multiple functions, functions that are “listening” when this Actions are being called.
On the Player script, we have 3 reference to call out when the player dies and it seems a little clutter.
Using a Action, with on line, we can “scream” that the Player has died and those who are “listening”, the script that need to know if the player has died, will execute the necessary functions.
On top of the Player script we need to use the namespace System
On our class we declare a Action<bool> called OnGetIsPlayerDead. Since mostly our reference needed to know if the player died and we pass a true or false statement the Action need to have a <bool> so it know that the functions listening are waiting for a bool data.
We add the new Action line and eliminate the other references
Listening The Action
The scripts “listening” for the Action need to know where they will accept the data when the Action on the Player script is being used.
On the SpawnManager script we need to have two new unity method, OnEnable() and OnDisable(). Notice where are using the IsPlayerDead() from the SpawnManager with no problem since the Action need a method / function with the same argument, in this case the method must have a bool argument to accept the data.
The UIManager script
The GameManager script
Adding The Restart Bind To The Input Action Map
Open the 2D_Shooter_InputActions map and press on the plus sign to add a Action
Named the new Action Restart and make his Action Type a Button
On the Path press Listen and hit the “R” key on your keyboard, select it and check mark Keyboard&Mouse and Gamepad
Will be changing were we are getting the inputs for our game.
Create a new game object named InputManager and add the Player Input component with a reference for our InputAction map and a new script with the same name.
Remove the Player Input component from the Player game object on the Hierarchy and update the script:
On the GameManager script
🎮PART 13 🎮