Clone using Instantiate() with only a subset of components

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!

You could try removing all the components that you want to add dynamically and add them in Init method, so you can decide whether given GO should have them or not

Thanks for your answer @pixaware_pwedrowski
Unfortunately that’s not a sustainable solution for me because I’d have to write many Init methods and generally go away from a prefab-based workflow. More importantly, the objects that I want to clone are built and combined within the game by the player, there’s a save/load feature in place and many things that I cannot or don’t want to fit inside an Init() function.

So to be more specific: Given any GameObject, how can I clone its hierarchy, but only include specific components like “Transform”, “MeshFilter”, “MeshRenderer”, etc. and/or exclude unwanted components.

Well, I have faced a similar problem in my project recently - I decided to create a new stripped prefab for every actual one so I can use it just for a visual representation. It worked well for me, but I’m aware that it is probably not an elegant solution

1 Like