Shooting Laser:

Sudarshan Thube
3 min readNov 8, 2021

--

So now our next step is to shoot Lasers from our Space ship. To shoot laser from our space ship we need to create Laser object.

First step is same as creating player object that is, right click in hierarchy window and go to 3d object and select “Capsule”, name it as Laser.

Create new 3d Object,Capsule.

Then Drag and drop enemy object from hierarchy window to project panel=> prefab folder. This will create Prefab (Prefabricated object) of enemy. We can use this prefab to spawn laser for our ship.

Make prefab of enemy object.

Create separate material for Laser in material folder. Assign new material to Laser object.

Create and Apply material to laser object.

To spawn any object at run time we use “Instantiate ” in unity. With the help of Instantiate we can spawn objects as well as we can also choose some properties for spawned object. like parent for object, spawn location etc. To use Instantiate we need to use prefab of laser and We need to add code in player script to, “Shoot Laser” from Ship when we press “Space key”.

Now,open Player.cs script, We have create variable for Laser Prefab. As bellow,

“SerializeField” allow us to see private variable in inspector, so that we can assign object to our laser game object in inspector. as bellow,

We can see Private field in Inspector.

After this we have to assign Laser Prefab which placed in Prefabs folder,

Assign Laser prefab in Player script.

We got our Laser prefab to use it in Instantiate. Now write code in Update so with condition where we can create laser when we press Space key.

This will check the key pressed event for space key.

Now check it by Play game,

Shooting Laser

As we can see in above, laser is spawning on pressing space key. We need to add movement code for Laser, so that it will move after get spawned. For that, Create new script naming “Laser” and attach/drag and drop it to Laser Prefab as we did for player.

In next article we will look into how to move Laser.

--

--