shoot laser beams: INSTANTIATE()

I want the player to shoot the laser beams from the spaceship when they press SpaceBar. The laser beams that are instantiated move forward in the Scene towards the Asteroids that are on the way. I have breaken down these behaviors into following steps:

I attached the MoveObjects.cs script into the LaserBullet GameObject. To get the forward movement behavior, first we should check the direction the object is pointing towards. Our Z-direction of the laser beams were pointed forward. So, using transform.Translate(Vector3 translation) I was able to move the laser beams forward. I used Time.deltaTime again to get my moving speed to units/second. The variable laserSpeed was set public so that I could change it later in the Inspector window. 

NOTE: Once it starts moving forward, the laser beams keep changing its z-direction infinitely. So later in this section I will discuss on how I destroyed them once they reach offscreen.

It is a good practice to create prefab of the objects that we want to instantiate. You can refer to Prefab section to understand what it is. The LaserBullet object, once it had the MoveObject behavior, was simply dragged and dropped into Prefabs Folder in the Project Window. 

Since, the instantiation of the prefab is performed when play presses SpaceBar, the behavior was included in the PlayerController.cs script. 

Always think about Decision Making statement, when getting an input from the user. 


To let UNITY know what GameObject to instantiate, we need to reference it to that gameObject. We can simply do that by declaring a GameObject variable and store the prefab as reference. 

Now that the GameObject reference was stored, following statement was added in PlayerController.cs Script to Instantiate the Object. In the if statement, we have a condition of player pressing SpaceBar. 

There are three types of Input for the GetKey

In our case, we want to fire the laser bullet when the user press down the spacebar. So I used GetKeyDown.

Instantiate (gameObject that we want to instantiate, position of the player, rotation of the prefab)

Now, every time the player hits the SpaceBar, the prefab LaserBullet is instantiated. The prefabs then move forward. We do not want to populate our system by leaving the instantiated prefabs moving infinitely. It might create a memory issue. So, the upper bound of the screen was identified and the bullets were destroyed once it reaches that limit. 

To do this, a new script "DestroyOffScreen.cs" to handle this behavior for different objects was created. Inside the script, an upperBound variable was defined. Using if statement, a decision to Destroy the gameObject was taken when it's z-position is greater than upperBound.

Syntax for Destroy in Unity:

Destroy(Object obj, float t = 0.0f);

Here, gameObject refers to the GameObject that the script is attached to.