Cleaning Up Your Code
Before adding any more features to the Space Shooter, let’s look at refactoring the code to have a clean and organized code to build off. I am going to show an example of each cleanup/organization of the code. For a complete look at the cleanup, you can check my GitHub for the project.
The first thing to change is all the “hardcoded” variables, and by that, I mean arguments that were set to a specific value that you can not change except by changing the value in the script.
The SpawnManager script will show the change of hardcoded variables by creating floats for the spawn delays and the range on the x-axis that objects can spawn.
With the values exchanged for the newly created variables, the code can be adjusted from Unity and anyone looking at the code now knows what each value does.
Now to show off required components. Using RequireComponent allows you to make components required on the GameObject that this script is attached. For the Player, I always want it to have AudioSource, and BoxCollider2D components, and the code for that goes in the Player script right above the class. Ideally, to have the script as modular as possible, you would want to use Collider2D instead.
With that added code, not only does it not allow you to remove the required components, but if you add the Player script to a new GameObject, Unity will add those components to it.
Headers are a great way to organize your variables so that it easier on the eyes when you need to change one of 20+ variables in Unity. To do this, use the Header function and pass in a string for the label above your variables.
With the Headers added to the Player script component, the variables in the Inspector are organized, making it easier for designers.
To keep Start clean in the Player script, I moved all of the code in Start to a new method that I call from Start. That will keep Start clear and make sure if there is a problem with code added in the future, it is not anything in Init. Also, since there will always be an AudioSource on the Player, the null check is no longer necessary.
That covers the code cleanup for now. In the following article, I will show adding a new feature to the game.