Add a copy of a object to Array

Hi im new to Programming and i have this problem with Arrays. I know how to Create and add to arrays but i dont know how to add a copy of a Object into the Array

what i mean is i have this GameObject that has some stats on it then i add that Object to the Array 2 times

the problem is when i modify the object in the array all of the objects get modified the same way

is there way that when i add the GameObject to the array it creates a copy then adds it to the array so when i edit array[1] array [0] stays the same even tho it was created from the same Object

You've run into what's known as "Referencing" in programming. An object, by default, is always passed around by reference. This means that no matter how many times you "copy" it or pass it around, it always points to the same location in memory, and it's always the same object (and only one of that object).

To create a copy of an object, you need to do what's known as cloning, though in Unity specifically, it's a bit easier.

With Unity, you can just Instantiate a new object based on the current one, which makes an identical copy of it.


// C#
GameObject myClonedObject = Instantiate(myObject) as GameObject;

// JS
var myClonedObject = Instantiate(myObject);

This creates a copy of the `myObject` object and places it inside the `myClonedObject` variable.