Playing God? Instantiating & Destroying within Unity.

Going back to the Space Shooter, I had to figure out how to actually make objects appear during the runtime of the game.

Now. I already have my Laser Prefab that I made before this so I needed to figure out how to have my Player Cube “Instantiate” (Spawn) this laser object.

As always, I had to make a variable first on my player script to hold the prefab I wanted to instantiate, in this case the laser. Next the code I ended up using was the following.

A simple “if” statement.

IF I press the space key, I instantiate my “prefab”, at the current position of my player, with a rotation of Quaternion.identity.

Quaternion is a very scary sounding word, but all you have to remember is that rotations in Unity use quaternions and Quaternion.identiy is just saying to use the default value! (phew)

Well its definitely instantiating and with some code that we learned from the player movement. I Just make a movement script for the laser prefab and….

Bam! (or should I say zzap?) we are now shooting empty space!

Now I know the laser is coming from the inside of the cube, that can be fixed with a quick offset in the code like this! Just + a new Vector3 to the position!

Now, there one big problem with all this however. I am creating, but a God can destroy as well no? Well if I don’t destroy this, this is just going to happen as well and that is no good for the program.

Endless TRASH!!

Within that Laser Script I talked about, I ended up creating a “if” statement to Destroy the object if its “y” position went past a certain amount. (Since the shots are going up)

I love it when things just make sense. Destroy(The thing I want to destroy) is just simple code, but I am sure I will be destroying many things while working on games.

With this the trash is seamlessly cleaned up and I am another step closer to a full fledged prototype!

I can’t wait to actually get to destroying enemy cubes!

See you all next time!