Creating a One Button Magnet Feature that Collects All Powerups — 2D Galaxy Shooter in Unity — Part 01!

Chris Hilton
3 min readAug 27, 2021

--

Objective: To implement a new feature that when you press 1 button, any powerups that are on the screen are automatically dragged towards the player like a magnet.

For this feature we are only going to work with code, so let’s open up the ‘Player’ script and get started!

Let’s first create a bool trigger switch for the coroutine running (the coroutine will handle the magnet cooldown timer).

Next, let’s create the MagnetActivated() method that is going to handle the player input detection for when the player presses the ‘R’ key. Within this method we are going to create an If, Else If statement that is going to firstly check whether the player has pressed the ‘R’ key and whether the magnet cooldown coroutine is not running. If this is true, then we are going to run the StartMagnet() method which is going to handle the bulk of the magnet operations and we will jump into shortly.

Secondly, we are going to check whether the ‘R’ key is pressed and whether the magnet cooldown coroutine is running. If it already is running (and the magnet feature is cooling down), then we are simply going to let ourselves know through Debug.Log. Later on I plan to add in a simple UI feature along with a Text feature that is going to pop up on the screen and let us know.

Let’s now run through the StartMagnet() method. Firstly let’s switch the bool trigger to true.

Next, we are going to search through the scene for any active game objects that have the tag ‘powerup’. This will return an array of game objects if any are found. Now we want to null check firstly to see if any were found and if they were we are going to dive into a for loop that is going to iterate through each game object and grab the ‘Powerups’ script component from them so we can call the Magnetise() method which is a bool trigger switch for the ‘Powerup’ script to start the powerup moving towards the player.

Lastly within this method we are going to check if the game objects found were equal to null and if so, we are going to run the coroutine that handles the magnet cooldown timer. We have this feature in the game to stop the player from spamming the ‘R’ key. They will need to be more tactical!

This is the modular MagnetCooldownRoutine() coroutine that is going to handle the magnet cooldown timer depending on when the player pressed the ‘R’ key. It also contains a simple bool trigger switch which is used in our player input MagnetActivated() method as discussed above.

--

--