Clone or duplicate an existing GameObject in Unity C#
In this tutorial, you are going to learn how to clone an object in Unity with the help of C# programming.
Below are the steps that I am going to follow in order to clone or duplicate a GameObject in Unity:
- Create an empty GameObject.
- Create a C# script that contains the necessary code to clone an object.
- Attach the C# script to the empty GameObject.
- Attach the script to the empty GameObject.
Let’s first create our C# script that needs to be attached to the empty GameObject:
using UnityEngine; public class DuplicateObject : MonoBehaviour { public GameObject objectToClone; void Start() { Instantiate(objectToClone); } }
Now the only thing we need to do is attach the GameObject to the Object To Clone field that we want to clone when the game start. Most probably you want to attach a GameObject already in the scene if you want to duplicate or clone an object.
So what we did do in the code?
Well at very first we have declared a public variable objectToClone
for GameObject. Then in the Start()
method of UnityEngine, we used the Instantiate function to create an object of objectToClone
variable.
Leave a Reply