Everything To Know About Unity Prefabs

Kenny Pruitt
Unity Coder Corner
Published in
4 min readFeb 22, 2023

Objective: Making, Adjusting, & Spawning Prefab Objects

To start making a laser attack, the first thing to understand is how prefabs work in Unity and how you can spawn them. First it is a good idea to make a dedicated folder for Prefabs, once this is done you can simply make a new gameobject in your scene and drag and drop it into your Prefabs folder. Doing so, will turn the object into a prefab.

Now that you have a prefab, you can edit prefabs as a whole in a couple different ways. One way is to make edits to your prefab in the scene and then simply click the Override button and click the Apply All button to apply your changes to all your prefabs.

Alternatively you could go into your prefabs folder, double click your prefab and make your changes to your prefab through the editor that way. It’s also a good idea if using this method to turn on the Auto Save function, that way any changes made to your prefab will automatically save.

To then spawn your prefab, you can just use the Instantiate function. You simply say, Instantiate(prefab, position, rotation), so you spawn the prefab and then tell it the position and rotation at which you would like to spawn the prefab.

Then to access the spawn function I can use the function Input.GetKeyDown(Keycode.specificKeyBeingPressed). In this case, because I want to shoot a laser when I press the space key, I’ll insert the space keycode into the function.

To test this to make sure it is working properly I can use the debug tool Debug.Log.

Then I can go into Unity press Play and have my console window visible, then each time I press the space key it will come up with a Debug.Log for the space key being pressed.

To make sure my console doesn’t get full of the same message over and over, I can also press the Collapse button to only show one with a number at the end displaying how many times the message has come up.

Now that we have verified our space key is working properly, we can now spawn the laser prefab using the space key. The first thing to do is make a reference on a script for the prefab like this.

Then in our FireLaser function we can simply instantiate the gameobject reference there.

Just as an extra note, always make sure you are assigning your prefab references in your scripts from your prefab folder, not from your scene. You can remove the prefab from the scene completely once this is done as well because you only want it to exist when you spawn it.

--

--

Kenny Pruitt
Unity Coder Corner

Unity Game Developer, C# Developer, and Software Engineer