Deep Copy Prefab

For some reason I can’t post questions on the answers section, so I’ll try here.

I’m trying to copy a component that has a reference to a Prefab.
When copying that component, it actually stores a reference to the reference for the prefab.
So when I destroy the original component, the prefab reference is gone from the copied component.

Is there a way around this?

My Copy Component method goes like this:

    public static Component CopyComponent(Component original, GameObject destination)
    {
        System.Type type = original.GetType();
        Component copy = destination.AddComponent (type);
        // Copied fields can be restricted with BindingFlags
        System.Reflection.FieldInfo[] fields = type.GetFields();
        foreach (System.Reflection.FieldInfo field in fields)
        {
            if (field.GetType() == typeof(GameObject)) {
                field.SetValue (copy, field.GetValue(original));
            } else {
                field.SetValue(copy, field.GetValue(original));
            }
        }
        return copy;
    }

If you need this in the editor only, you could use SerializedObject and CopyFromSerializedProperty.

See the CopyInternal method for an example, where an entire SerializedObject is copied.

Thanks for the reply.

Yeah the thing is I really need this in runtime, I should have specified that.

Have you tried caching the reference, maybe setting it as null (on the source to be copied) before copying the component, and then re-assigning it to the new copy?

If anyone cares, I ended up loading all the items into a Dictionary in the beginning of the game, and in the Add Component method, I check for a game object, and if it’s true, I just grab the item from the Dictionary.