To spam, or not to spam?

Andrew Alteri
2 min readJun 13, 2021
Many Many dogs on screen

Unity hid a crucial element of video game programming in a bonus challenge of the Junior Programmer: Create with Code 1 course! The challenge was part of a “fetch” game: balls fall randomly from the sky, and the player must send their dog out to catch them before they hit the ground. The game is pre-built at the beginning of the tutorial, but it is buggy and broken. I fixed most of the bugs, but one remained: the player could spam the spacebar to create an endless number of dogs. This eliminates any challenge for the player and breaks the game. Although Unity hid this bug in a bonus challenge, it is actually a common problem that developers face. With a strong desire to learn how to eliminate spamming in games, I decided to take on this challenge.

My final code is below. At first, I could not figure out how to solve this coding challenge, but by searching online, asking the right questions, and reviewing similar problems I faced while making a Pygame video game, I came to a solution. This is only one of the ways you could solve the spam predicament. Please let me know if you have found a different approach!

At the top, I created three variables: a dog object and two floats that keep track of time and the timer. In the Update() method, I set the timer variable to increment on Time.deltaTime. This will start the digital timer. As the timer ticks away, I use an if statement that spawns a dog on the press of the spacebar if the timer is greater than or equal to 1, the initial value of time. Once the spacebar is pressed, the timer will return to 0. So, to recap, the time is initialized at 1.0 and the timer is initialized at 0. Once the timer becomes greater than or equal to 1.0 second, the player can press the spacebar again which will instantiate a new running dog. This way, the player is limited to one dog per second.

During this challenge, I learned how to prevent a player from spamming a key/button, making the game more challenging. I also learned that sometimes we overthink the problem while coding. The solution here was a simple timer and a short if statement. Programming does not have to be complex; it just has to work. Happy coding and keep creating!

--

--