- Home /
Array variable assigned to instantiated object changes in all instantiated objects?
Hi, I'm having an issue with setting up variables in an instantiated object. It appears that when I try to setup an Array variable in the instatiated object, it works the first time, but when I create anymore of the same object, the array variable is updated in all of them.
Whats frustrating though is that other variable types (i.e int
, float
etc) stay unique to the instance.
I came across this question, which suggests the problem might be that I'm changing the variables inside the prefab itself and not the instantiated object, but it doesn't seem to work with arrays.
Here is the relevent code: (with variable and function names changed for convienence)
MainController.js
: Added to an empty GameObject in scene
var prefabToInstantiate : InstanceControlScript; private var array1 = Array(arrayLength); private var array2 = Array(arrayLength); private var someOtherVar : int;
//Some code which sets data in arrays and calls CreateInstance() when Fire1 is pressed
function CreateInstance(){ var newInstance = Instantiate(prefabToInstantiate, pos, rot); newInstance.arrayX = array1; newInstance.arrayY = array2; newInstance.someInteger = someOtherVar; }
I drag the prefab with the script below onto the prefabToInstaniate field in the inspector
InstanceControlScript.js:
private var arrayX : Array; private var arrayY : Array; private var someInteger : int;
function Update(){ //some code which reads and acts to the new arrays and variables }
Any help will be greatly appreciated!
Not really an answer, but have you tried using .Net arrays?
Answer by Eric5h5 · Jul 11, 2010 at 02:07 AM
Arrays are by reference, not value. Assigning an array to a variable merely creates another reference, it doesn't make a new copy.
@aLyon: $$anonymous$$ake a new array and copy all the elements from the original array. If you use an ArrayList ins$$anonymous$$d of Array then there's a Clone() method.