In my project, I have units that move following a path of points, each one has a different group of points. When I create the instance of the Unit prefab I set the points:
var unit : GameObject[];
var points: Transform[];
function CreateUnit (){
...
unit *= Instantiate(UnitPrefab, StartPoint, Quaternion.identity);*
points[0] = GameObject.Find(“Point0”).transform; points[1] = GameObject.Find(“Point1”).transform; unit*.GetComponent(Unit).SetWaypoints(points);* … } Then, in the Unit class the points are assigned to the variable waypoints: var waypoints: Transform[]; function SetPoints (list:Transform[]){ * waypoints = list;* } But each time this cycle (create unit, assign points) is called, it modifies the waypoints of all instances, instead of only the most recently created. waypoints is not a static variable, and this doesn’t happen with any other variables (like health or speed). Why does this happen?
This is caused by fact that arrays are reference types, while your health, speed, etc. are probably float/int which are value types.
In your CreateUnit function, you set points[0] and points[1] of already initialized array. You’re then passing this array to a SetPoints (or SetWaypoints), and this whole array is then assigned to waypoints variable.
For first unit it works ok, but when you call CreateUnit again, and set both points, then they’re set in previous Unit instances as well, because points array in your unit manager, and waypoints array in all Unit instances are all the same arrays (or should I say “the same array”).
To best way to solve this, is initializing points inside CreateUnit:
points = new Transform[2];
points[0] = GameObject.Find("Point0").transform;
points[1] = GameObject.Find("Point1").transform;
You can also make some change in SetPoints method, and instead of assigning the whole array, just initialize waypoints to a new array, and then copy elements.