12

Is there a C# way in Unity to duplicate an existing GameObject and all of its children? In my case, I have an empty GameObject with a number of Text objects as children and I would like to create a copy of them all, including relative positions, text values, font, colors, etc....

Prefabs won't work easily because I want to copy the object including its current state.

Programmer
  • 121,791
  • 22
  • 236
  • 328
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31

2 Answers2

23

The Instantiate function is used to clone any GameObject and its hierarchy.

public GameObject rootObj;

void Start()
{
    GameObject duplicate = Instantiate(rootObj);
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
-4
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class main : MonoBehaviour
    {
        public GameObject hk;
    
        void Start()
        {
            hk = new GameObject("I am hk");
        }
    
        void Update()
        {
            hk = new GameObject("I am hk");
        }
    }
drk1
  • 65
  • 11