clearing an array

I just spend 2 hours bouncing my head against the wall trying to figure out what was going on with some scripts when I found it had to do with populating arrays:

var arr =  = new Array();


function DoSomeStuff(){
   // be sure the array is emtpty
   arr.clear();
   // some code to populate the array
   // the array will look something like this (4,2,3,1)
   ..
}

Each time I run the scene in game view the function above is called at start up. But what I found is that actually the array doesn´t get cleared from the previous run. Each time it pushes the new array elements to the array. So after running the scene 3 times under the same circumstances the array above will look like (4,4,4,2,2,2,3,3,3,1,1,1).

Only when simply resaving one of the scripts in the project folder (even when not making any changes), the array gets cleared. Is this what is supposed to happen?

First of all, the surest way to clear an array is arr=new Array();

But that final result is very strange. What does your “populate the array” code look like?

The array is populated by taking it´s length for the next element:

arr[arr.length] = something;

Probably well known to everyone (and now to me) I had encountered similar issues when trying to copy an array.

When I

  1. set the first array equal to temp_arr,
  2. cleared temp_arr with temp_arr.clear() then read in new file data
  3. set the second array to temp_arr,

I found that the first array also contained the second array data.

The solution I found was to use
second array = firstarray.Concat(temp_array) which left the first intact and gave me the expected array structures.

Related - may save others some time.

Regards,

PW