Copy GameObject in C#
I have a trouble Copying a game object. I'm trying to create many game objects, calculate position for each of them, and then use Instantiate to display each object in the scene.
Here is a test code that I've made to clarify the problem in details.
GameObject spawnObject1 = new GameObject();
spawnObject1 = _spawnObject;
spawnObject1.transform.localPosition = new Vector3(-100, 10);
Debug.Log("Logging gameObject 1: " + spawnObject1.transform.localPosition);
GameObject spawnObject2 = new GameObject();
spawnObject2 = _spawnObject;
spawnObject2.transform.localPosition = new Vector3(100, -10);
Debug.Log("Logging gameObject 1: " + spawnObject1.transform.localPosition);
Debug.Log("Logging gameObject 2: " + spawnObject2.transform.localPosition);
This is the output
This happens because _spawnObject isn't cloned to spawnObject1 or spawnObject2. They are using the same instance. I know I can use Instantiate after I have calculated position for each object, then calculate position for next and so on... but before I do that I really want to know if this approach is possible somehow.
When you do new GameObject()
you make a fresh copy of a GameObject so why would you want to reuse the reference to the first instance when what you really want is another unique instance?
Your answer
![](https://koobas.hobune.stream/wayback/20220612114500im_/https://answers.unity.com/themes/thub/images/avi.jpg)