Javatpoint Logo
Javatpoint Logo

Understanding Prefabs and instantiation

Instantiating and destroying characters or objects is very common in any game. Instantiating means bringing the object into existence. Objects appear or spawn or generate in a game, enemies die, GUI elements vanish, and scenes are loaded all the time in the game.

Prefabs are very useful when you want to instantiate complicated GameObjects or collection of GameObjects at run time. Compared with creating GameObjects from scratch using code, instantiating prefabs using code is better, and it has many advantages.

Let's understand what prefabs are; since prefabs are considered important to understand how instantiation works in Unity.

Prefabs are like blueprints of a GameObject. So we can say, Prefabs are a copy of a GameObject that can be duplicated and put into a scene, even if it didn't exist when the scene was being made; in other words, prefabs can be used to generate GameObjects dynamically.

Let's create a prefab; for this, you need to drag the desired GameObject from your scene hierarchy into the project Assets.

Understanding Prefabs and instantiation

Now, to instantiate a GameObject, we call the Instantiate() method in our script. This method is available in MonoBehaviour, takes in a GameObject as a parameter, so it knows which GameObject to create or duplicate. It also has different overrides for changing the newly instantiated object's transform, as well as parenting.

Now create a new script called Instantiator.cs and copy the following code in it.

In the above program, we used the GetKeyDown method of the Input class o check if the player pressed a specific button during the last frame. The GetKeyDown() method returns true if the key specified by the KeyCode enum (which is used to list all possible keys on a standard keyboard) is pressed in that frame.

Save the script. And now, create an empty GameObject by right-clicking on the scene from the Hierarchy tab.

Understanding Prefabs and instantiation

Attach that script file (Instantiator.cs) to the newly created GameObject's Component from the Inspector tab.

Now, in the Diamond variable drag that prefab we have created.

Understanding Prefabs and instantiation

When you run the game now, pressing the Spacebar will create a new Diamond object identical to the one we used to create the prefab. You can see each diamond is created in the object hierarchy. The reason you can't see them show up in the game is that for the time being, they are all being created exactly one over the other. But you can verify it from the Hierarchy tab. Each time when you press a space bar, it will show in the tab as a Diamond (clone).

Understanding Prefabs and instantiation




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA