x


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

more ▼

asked Mar 28 '10 at 04:45 AM

Rufalo gravatar image

Rufalo
65 5 6 13

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Mar 28 '10 at 07:13 AM

qJake gravatar image

qJake
11.6k 43 78 161

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

Mar 28 '10 at 03:40 PM Rufalo

It's not easy to clone a class via programming, 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.

Mar 28 '10 at 09:45 PM qJake
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5061
x352

asked: Mar 28 '10 at 04:45 AM

Seen: 3396 times

Last Updated: Mar 28 '10 at 04:45 AM