Hey, I’m reasonably new to Unity and C# so this is probably just a novice mistake but I’m hoping someone can help me out.
I am trying to create an array/list (still not clear on C# terminology, I think it’s an array though) populated randomly with 0s and 1s. This is done in GenTrialList(). I then want “copy” this array (called trialList) into orientationArray, and then for each element in the array I want to change a percentage of them from 1 to 0 or vice versa - currently I have this at 80%.
Most of the code works fine, however when I run ReliabilityModifier() in Awake(), it changes both trialList and orientationArray, and I can’t figure out why it is overwritting trialList. I’ve attached the code below, as well as some print functions in Start() that show it is not working as I would like.
public static class OutputData
{
public static int[] trialList;
public static int[] orientationArray;
}
public static float perc = 80;
public int numTrials = 10;
public void Awake()
{
OutputData.trialList = GenTrialList(numTrials); // Generates the trial list
print("trial list original:" + string.Join(",", OutputData.trialList));
OutputData.orientationArray = OutputData.trialList;
OutputData.orientationArray = ReliabilityModifier(OutputData.orientationArray, perc);
}
public int[] GenTrialList(int numTrials)
{
int[] trialList = new int[numTrials]; //
System.Random r = new System.Random();
for (int i = 0; i < trialList.Length; i++) //(start; end; step size)
{
trialList[i] = r.Next(0, 2);
}
return trialList;
}
public int[] ReliabilityModifier(int[] array, float perc)
{
double modi = (perc / 100) * array.Length;
int[] percArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Shuffle(percArray);
for (int i = 0; i < percArray.Length; i++)
{
if (percArray[i] >= modi)
{
if (array[i] == 1)
{
array[i] = 0;
}
else if (array[i] == 0)
{
array[i] = 1;
}
}
}
return array;
}
void Start()
{
print("trial list:" + string.Join(",", OutputData.trialList));
print("orientation array: " + string.Join(",", OutputData.orientationArray));
}
I have tried messing around with it a bit, like just having the following instead of it being split over two lines:
OutputData.orientationArray = ReliabilityModifier(OutputData.trialList, perc);
I could guess that it has something to do with the return statement in ReliabilityModifier, or the way I am populating orientationArray in Awake(), but I’m not experienced enough to be able to figure out what to change and thought I’d ask here. Thanks
edit: I also realize that there are probably a lot of examples of poor practice within the code I provided, I’d also appreciate any advice on how I can write this code better in general.