Hi there,
I would like to clone a GameObject (GO) including its hierarchy, but only clone a specific subset of Components present on the GOs. The following code is working, but it’s just instantiating the original GO, thus cloning all the components, too. Unfortunately, this also triggers some of the lifecycle functions (OnEnable, Awake, I believe), which I don’t want.
public static GameObject CloneIncludeComponents(this GameObject o, List<Type> allowedTypes, bool worldPositionStays = true)
{
// Clone whole hierarchy
var newGO = GameObject.Instantiate(o, o.transform.position, o.transform.rotation);
// Get a list of all components, including deactivated GameObjects
var components = newGO.GetComponentsInChildren<Component>(true);
foreach (Component c in components)
{
// See if the component in question is contained in the allowed types and Destroy if not
if (!allowedTypes.Contains(c.GetType()))
{
GameObject.DestroyImmediate(c);
}
}
newGO.AddComponent<ClonedHierachy>().Init(o.transform);
return newGO;
}
Is there a way to do the same and only clone the “naked” GO hierarchy and then add the components that are “allowed”? More specifically to my case: I’d like to click an object in my game and get hold of a purely visual representation of it. For example, to move the original to another position, I’d like to show the user a see-through version of it first and when he/she is happy with the new position, I can move the original and delete the visual aid.
Thanks for your help!