- Home /
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
Answer by qJake · Mar 28, 2010 at 07:13 AM
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.
Thanks but i have little problem that method Works Perfect with GamObjects but how do i Clone Classes? like if i have a Character Class and i want to add NewChar:Character to an Array Instantiate did not work
It's not easy to clone a class via program$$anonymous$$g, and it's not widely used. There are two forms of cloning - high level and low level cloning. I don't know what your code looks like, but I assure you, there's about a 99% chance that cloning is NOT what you're looking for. You should try and instantiate multiple objects if you want multiple instances of the same type of object.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Why does unity expect a file when I try to put text on a mesh? 1 Answer
How can I check values of all array/List quickly 1 Answer
I'm trying to sort my Npc's into different social classes 1 Answer
Attempting to add object to dynamic array causing problems 1 Answer