We want to spawn, or instantiate, our laser bolt prefab from the tip of our ship when we press the “fire” button.
To instantiate a Prefab at run time, your code needs a reference to that Prefab. You can make this reference by creating a public variable in your code to hold the Prefab reference. The public variable in your code appears as an assignable field in the Inspector. You can then assign the actual Prefab you want to use in the Inspector.
In our player script we do just that, declaring a public GameObject variable as laserPrefab, which then allows us to drag our GameObject of choice into a nifty little inspector field.
CAUTION: be careful to drag the prefab from the PROJECT window, NOT THE HIERARCHY.
In fact, just delete that li’l nasty freak from the hierarchy right now, y’hear?
Go ahead and make the prefab private and serialize the field for good measure.
Now about that instantiation…
First off, we need some logic to make it happen via pressing the space key.
We need to access the Input component when a Key is pressed down
Then we need to know which key, hence:
So if the space key is pressed, the code inside is run — in this case, a debug command to test the functionality.
Functionality works, we’ve got our prefab loaded, let’s instantiate dis bish.
Delete the debug and make your code like this instead:
Let’s dip into the game and see what happens:
Mkay. So you see those Laser(Clone) objects popping up in the Hierarchy? That shows the code is working. But the laser bolts are only instantiating in one place — LocationZero. That’s the default location.
We still need to give the laser speed, direction, and make it originate from the spaceship.
So let’s expand our code a bit:
Now the code is telling the game to instantiate a _laserPrefab from the spaceship’s position component in its transform component, and to keep it from rotating as we don’t need that (we can dive deeper into Quaternion.identity another time).
Let’s see what happens now (it’s kinda neat):
It’s like the reverse Pac-Man!
Or the natural result of Pac-Man’s primary activity.
So this could be useful for a different kind of game, but not for our particular porpoises.
Join me next time as we instill some proper behaviour into the prefab by coding in some…behaviour!