Day 5: Prefab, when to use it

Today I talk to you about prefabs. Prefab is a component of unity that allows to create, configure and store a GameObject complete with all its components.

There are several reasons to use a prefab, a non-player character, an element that is repeated in your environment like a tree or a group of them, bullets. Any type of game object that you think can be used more times you should convert into a prefab, it is much better than copying an object in the scene.

To create a prefab, just drag an object into your scene, in the Project tab. It is better to put it in a special folder called Prefabs to keep the project clean.

Once created you can remove it from the scene, and recall it through the Instantiate command of unity.
This method asks you, the gameObject you want to instantiate, its position, and rotation.

Instantiate(gameObject, position, rotation)

In my case, we are talking about bullet prefab, so my goal is to have them appear in a position related to my player. Once it has spawned it follow its behavior.

For this reason, in my Instantiate call, I have inserted the position of my player with an offset editable in Inspector that allows me to manage the proximity to the player

Using prefabs allows you to easily update all elements or create a specific behavior, but be careful not to override it, otherwise, all prefabs of that specific object will have the same behavior.

You can also use this system for the player, its prefab might be placed at the starting point on each level of your game.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store