Skip to content

Instantly share code, notes, and snippets.

@Scraft
Created October 10, 2016 13:09
Show Gist options
  • Save Scraft/0c647015aa21bf29bcc094e2b617a773 to your computer and use it in GitHub Desktop.
Save Scraft/0c647015aa21bf29bcc094e2b617a773 to your computer and use it in GitHub Desktop.
Cloning game objects in UI hierachy
private static void CopyComponentInternal(Component original, Component destination)
{
if (original == null || destination == null)
{
//Debug.LogError("Null Objects in copy");
return;
}
Type type = original.GetType();
//if (type != other.GetType()) return null; // type mis-match
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
PropertyInfo[] pinfos = type.GetProperties(flags);
foreach (var pinfo in pinfos)
{
if (pinfo.CanWrite)
{
try
{
pinfo.SetValue(destination, pinfo.GetValue(original, null), null);
}
catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
}
}
FieldInfo[] finfos = type.GetFields(flags);
foreach (var finfo in finfos)
{
finfo.SetValue(destination, finfo.GetValue(original));
}
}
private static void CopyComponent(GameObject original, GameObject destination)
{
RectTransform MainItemTransforms = original.gameObject.GetComponent<RectTransform>();
RectTransform itemTransforms = destination.gameObject.GetComponent<RectTransform>();
CopyComponentInternal(MainItemTransforms, itemTransforms);
for (int i = 0; i < original.transform.childCount; ++i)
{
CopyComponent(original.transform.GetChild(i).gameObject, destination.transform.GetChild(i).gameObject);
}
}
public static GameObject CloneUIGameObjectHierachy(GameObject src)
{
GameObject go = GameObject.Instantiate(src);
go.transform.SetParent(src.transform.parent, false);
CopyComponent(src, go);
return go;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment