- Home /
Question by
popyd10 · May 04, 2020 at 09:55 AM ·
arrayarray of gameobjectsstruct
Changing one array element changes the rest
for (int i = 1; i < GenSize; i++)
{
cars[i].GetComponent<Brain>().neurons[0].weights[0] = i;
}
should set the first weight of the first neuron in each car's brain to the car's index number, but at the end of this loop, all cars' first weight of their first neuron contain the index of the last car. (eg. all store 49 if the array has 50 cars) Why would this happen? Here is the code for the neuron struct as well (the weights are all initialized before the above loop runs):
[System.Serializable]
public struct neuron
{
public float[] weights;
public int size;
public float rawOut;
public float output;
};
Comment
Answer by FlaSh-G · May 06, 2020 at 05:12 AM
The loop looks fine, which means that your issue likely comes from reference semantics pulling a sneaky on you. Is it possible that you assign the same array (rather than an equal one) to each neuron?
A minimal example:
var friends = new Person[2];
// assign some people as friends here...
var personA = new Person(friends);
var personB = new Person(friends);
personA.friends[0] = someoneElse;
if (personB.friends[0] == someoneElse)
{
Debug.Log("They both changed friends because they use the same friends array rather than each having their own.");
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612233035im_/https://answers.unity.com/themes/thub/images/avi.jpg)