- Home /
List elements all changing
I have a list of type Foo. I create one Foo object and add it to the list. Foo has a Copy() method whereby it is supposed to create a new Foo object and assign all of its values to the new object and then return the new Foo object. That new Foo is then added to the list. After the new Foo is added, some of its member values are randomly changed, and here is where it gets crazy. When a value on the most recently copied Foo is randomly changed, the values of that member are changed on all of the other copies of the Foo. Does anyone have a clue why?
I think I might understand the problem, the copy you're doing is a shallow copy which shares the same memory address as all other Foo's. What does the Copy() method look like?
function Copy() : DiscreteTrait { var newTrait = new DiscreteTrait(trait,a1,a2); newTrait.$$anonymous$$utate(); return newTrait; }
a1 and a2 are the Foo objects I was mentioning. 'trait' wasn't being affected.
If I understand your response correctly, a1 and a2 are memory addreses of the object, and so any changes are being applied at the addresses of the original object?
Sorry for the delayed answer, it was late over here. :-) I wrote an answer below, I'm no computer scientist but from what I understand your issue is that your objects are addressed to the same object in memory and makes them become dependent.
Answer by save · Aug 18, 2013 at 10:35 AM
If changes are being applied to all of the objects when you change one, the reason is that they are addressed to the same origin and are just 'mirrors' of that same object cached in memory.
What you can do is to iterate through a Foo and return a fresh instance of it, it's a bit of a workaround but a shortcut considered what kind of reflection you might have to use instead if your 'bars' isn't that many. Here's an example of what you can do:
private var fooList : Foo[];
function Start () {
// Create the Foos
fooList = new Foo[2];
for (var f in fooList)
f = new Foo();
// Set a value for Foo[0].bar
fooList[0].bar = 1337;
// Copy Foo[0] into Foo 1
fooList[1] = Foo.Copy(fooList[0]);
// Set Foo[0].bar to 0
fooList[0].bar = 0;
// Log what happened, Foo[0] should be 0 and Foo[1] should be 1337 if they are independent
for (var x = 0; x<fooList.Length; x++)
Debug.Log(fooList[x].bar);
}
class Foo {
var bar : int;
// This is what you would do to create an independent instance:
static function Copy (fooCopy : Foo) : Foo {
var returnFoo : Foo = new Foo();
returnFoo.bar = fooCopy.bar;
return returnFoo;
}
}
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Variable Scroll How do I make it Scroll 1 Answer
Question About Clone 0 Answers
sort List alphabetically 2 Answers
Creating a list with trigger 1 Answer