Setting arrays equal to each other issue

Hi,

when I want to make tempArr = masterArray, it works. However, when I change the contents of tempArr, the masterArray follows suit.

In my program I want the master array to be the unchanging list of data for the temp array to refer too. In my program I have this:

for (var i : int = 0; i<masterArray.length; i++){
	tempInt = Mathf.Round(Random.Range(0, tempPosArray.length)); //random index
	tempArrayP *= tempPosArray[tempInt];* 
  •   tempPosArray.RemoveAt(tempInt);*
    
  • }*
    tempPosArray = masterArray;
    This function makes a new array(tempArrayP) which is the same thing as tempPosArray with a randomized order. In order to make this happen, I pick a random element out of the array, I plug it into the new temp array and remove it from the old one So that there are no duplicates.
    The problem: when I remove elements from tempPosArray, those same elements are moved from masterArray as well…and WHY? masterArray is on the left side of the equal sign…I just don’t get it. is there a way to make masterArray concrete, unchanging. masterArray is set in the Start (); function.

Using the assignment operator, you are actually just referencing the original Array. To make a copy, instantiate the new array with the same size as the source array, then iterate through the original array and assign the individual values to the same index within the new array.

You have to understand that arrays are reference types. That means, that they don’t actually store values, they only store references to those values. So when you have a line of code like

tempPosArray = masterArray; // called before  your function as well I suppose

what you actually do is copying a reference to a memory location, meaning that any changes to the memory at that location (including removing elements) will be reflected in both arrays. That was the “why” part.
Now to change this, just use

tempPosArray = Array.copy(masterArray, tempPosArray, masterArray.Length);