Spawn a Prefab in Unity 3D with C#
In this tutorial, you are going to learn how to spawn a prefab in Unity 3D with the help of C# programming.
In game development, it is a common thing to create GameObject at runtime with the help of C# programming. For example, you may create bullets while firing or spawn new enemy characters during GamePlay.
In order to create GameObject from the prefab, you have to create the reference variable of the object and Instantiate when you need as you can see below
using UnityEngine; public class GameManager : MonoBehaviour { // This is reference to the prefab. The prefab needs to be drag and drop to this field. public GameObject playerPrefab; void Start() { // Spawn the prefab at the given position (0, 0, 0) Instantiate(playerPrefab, new Vector3(0, 0, 0), Quaternion.identity); } }
Now you have to create an empty GameObject and attach the above script to that object. Now you can see the Player Prefab variable field in the inspector:
Here you have to drag and drop the prefab you want to appear in the game when the game starts. If everything goes right, you can see the GameObject or prefab spawn at runtime.
Leave a Reply