Objective: Instantiate a moving projectile prefab pressing Space and destroying it when reaching certain position on the Y Axis
If you want to check our Player movement implementation click HERE
Requisites: Player(cube) and player behaviour script, projectile prefab and projectile behaviour script.
First of all we are going to create our projectile, in this case we will choose a 3D object capsule, rename it to Laser and scale it to 0.2 in the XYZ values. Drag it to the Assets folder to convert it to a prefab and delete it from the scene
Important: Instantiating means creating an object clone as many times as we want so we don’t have to make 25 individual different projectiles, we can make a copy of the original one 25 times if needed.
On our player script we’ll need a laser prefab reference to instantiate it:
Good practices in programming say that we should always keep every variable private unless the value is going to be accessed and modified by an external script.
On the Update method with the condition and the Input.GetKeyDown function we can define a key we want to check if pressed on our keyboard.
There are 3 parameters we want to include in the Instantiating function:
- The object: For this we pass into the funcion our laser prefab reference
- The position: We want the object to get instantiated in the same position as our player.
- The rotation: We don’t want to modify the rotation of the object
Now we can save and move into the Unity Editor, select our player and into the Player script component drag the Laser prefab to define the object reference.
Time to move into the laser behaviour, let’s open the laser script.
Private variable but modifiable in the inspector, remember the good programming practices!
transform.Translate to move our projectile when it gets Instantiated
We will give the projectile a vertical velocity with a Vector3.up multiplied by the speed we choose on the Editor and Time.deltaTime to fix the crazy velocity.
With the Destroy function when the position of the projectile goes above 8 units it automatically gets destroyed.
Last step is dragging the Laser behaviour script into the Laser prefab, giving it a speed value and that would do the task!
IMPORTANT: This instantiating method works totally fine but there is a more optimal way to do this with a design pattern called Object Pooling. We are not getting into this more advanced concept but if you really care about performance, you should definitely check it out!