In this and the next section, Students learn how to implement physically simulated cannonball projectiles as a part of the Castle Attack project.
In this section, our goal is to create a physically simulated cannon ball projectile. To accomplish this we’re going to write a new C# script called Projectile.
Create a new project using the 3D core template. You can name this project whatever you like, I named my version of the project Castle Attack but you’re welcome to change it if you’ve got a better name in mind.
We’ll start by setting up our default sample scene with the following GameObjects:
The purpose of our Projectile script is to launch a GameObject forward like a cannon ball. If you’re up for a challenge and are reading this before watching the video, you can try and write this script on your own following these guidelines:
Whenever we’re working with different component references in our scripts, there’s often a possibility that one or more of these references will be unassigned. If we try to access any data members from an unassigned reference, we’ll get an Unassigned Reference Exception error, which will either stop our game from running or disable the script that caused the error.
In Unity C# scripting, Attributes are markers that can be placed above a class, property, or function to indicate special behavior. Attributes are denoted by the  square brackets.
[RequireComponent] is a type of attribute that allows us to specify that a script requires a certain type of component in order to run. When we add a script with this attribute to a GameObject, if a component of that type does not exist, one will be added automatically.
In the example below, the Projectile script would require any GameObject it’s attached to, to have a Rigidbody component as well.
In order to avoid having to set each reference variable ourselves in the editor we can instead use GetComponent to return a reference to a component of type attached to the same GameObject as the script.
If there is not a component of the chosen type attached to that GameObject, then GetComponent will return a null reference. However, if our script is also using [RequireComponent] we can be sure that GetComponent will return a valid reference.