Western Shooter Devblog #2 | Instantiating & Destroying Gameobjects in Unity
Instantiation and destruction, to create and to destroy… we really do play gods don’t we? Well either way, I gave Cubert a gun and he intends to use it so let’s get started shall we?
I gave our scene a simple little prototype environment to give us a better feeling of perspective and to block out the look of our game a little better.
And I’m sure Cubert appreciates being a little taller as well.
So here’s Cubert’s gun, I know… it looks great. But the only problem is that it doesn’t shoot. So what do we need to do?
We can’t shoot a gun if we don’t have bullets so let’s make some rounds!
NICE. Now let’s make this thing fly!
We can very easily just make a modified version of how Cubert moves.
The only thing we changed here, is instead of waiting for the player input, the bullet will immediately start moving forward the frame it is Instantiated.
Cool! Now we just need to be able to fire it on command! To do this, all we need is our Pistol to be able to Instantiate the bullet, and then our Player needs to be able to communicate with the Pistol, to fire it! Some things are easier said than done, but this was actually easier done than said! I was able to do this in just a few lines of code!
First I created an empty game object that will just act as the position that I want the bullet to instantiate from, right in front of the gun!
Then I made a simple Pistol script that just takes the PistolRound prefab and Instantiates it at the BARREL END transform whenever the Fire() method is called.
Lastly, the Player will call the Fire() method whenever the player hits the Space button.
And we’re done!
But with every creation, comes destruction. These bullets are being instantiated but will continue to fly forever, so let’s fix that by destroying them once they reach the end of the level.
Instead of creating a giant “death box collider” at the end of level, I instead made a simple timer that will destroy the PistolRound prefab after 3 seconds. That way no matter what happens, the bullet will always be reliably destroyed after a certain amount of time has passed.
And we’re done! Cubert and his new gun are now an unstoppable force! However I think we need to do something about how fast he can shoot that gun… hmm…
We’ll figure that out in my next devblog where we are gonna make a cooldown system for the fire rate of Cubert’s gun!