Deep clone a gameobject

I tried searching around for this, but I wasn’t able to find an answer.

I have a gameobject with a custom component attached (C# script). This script has several variables that have been set previously (Lists, booleans, etc). I need to make a clone of it.

Now, when I Instantiate a new object from this one, I have noticed that none of the variables from the original are copied over; the component is in a fresh state in the new one.

Is there a way to perform a deep clone of a gameobject? A clone where the state of every attached component is identical to the original, including members?

EDIT:

Here is some example code to demonstrate the issue (the original code is far too verbose)

public class FooBar : Monobehaviour {
    private HashSet<uint> hashSet;

    public void Awake() {
        hashSet = new HashSet<uint();
    }

    public void SomeMethod() {
        hashSet.Add(12345);
    }
}


// code in some other class
gameObjectWithFooBarComponent.SomeMethod();
GameObject go = Instantiate(gameObjectWithFooBarComponent);

If I set a breakpoint in the code in the Awake() method, hashSet is null before assigning it a new hashSet. I want it to have a single element “12345”, which is what the object I cloned from has.

are the variables set at runtime?
In the editor you have to assign gameobject itself rather than a prefab to the instantiating script…
this will copy the current variable values at runtime.

Awake gets called on an object as it is instantiated.

You’re calling SomeMethod on the original object modifying its data then proceeding to instantiate a copy of it. Then the newly instantiated copy is calling Awake and re-initializing the list, losing your values in the process.

Try this:

public class FooBar : Monobehaviour {
     public HashSet<uint> hashSet = new HashSet<uint();
 
     public void SomeMethod() {
         hashSet.Add(12345);
     }
 }

Update: Actually, aside from what I mentioned above, Unity will not copy over private or protected members when you create a new copy. It will only copy public members, which makes total sense. You might need to rethink what you are doing vs what you are trying to accomplish.