Random struct doesn't update after NextFloat unless it's copied

If I set the destination X and Z values using a reference instead of a copy, the Random struct doesn’t seem to update after each NextFloat call.

For instance, if I set the values like this…

destination.Value.x = randomArray[nativeThreadIndex].NextFloat(0f, 100f);
destination.Value.z = randomArray[nativeThreadIndex].NextFloat(0f, 100f);

…then the x and z values are identical (eg, [31.52221, 0, 31.52221] )

However, when I set X and Z by copying the Random and then copying back into the array (like the instructor), then it works as expected (again, like the instructor’s):

var random = randomArray[nativeThreadIndex];

destination.Value.x = random.NextFloat(0f, 100f);
destination.Value.z = random.NextFloat(0f, 100f);

randomArray[nativeThreadIndex] = random;

My question is why? Why is the behaviour different?
If I’m using the Random struct through a reference, I would expect it to be operating equivalently to a copy of it.

(Note, I’m using the same packages as the instructor in the course)

When you access randomArray[nativeThreadIndex] you’re only (necessarily) getting a copy of the random. Anything you do to it (like NextFloat) will have no effect on the actual element. In the case of your first fragment of code, you’re accessing the same random twice in the same state, but you’re only working with a copy which is immediately discarded before moving to the next line.

When we grab that copy and cache it, then we can affect change on the copy and write the copy back to the randomArray.

This is similar (but not for the same reasons) to what happens with transform.position.
You can set transform.position to a Vector3, but you can’t say transform.position.z=0; For that you have to grab the transform.position as a Vector3, modify it, and then write it back to Transform.position.

I see. So, I’m not actually accessing it as a reference.

The behaviour does make sense in that case. Making a local copy, operating on it, and then saving it back all behave as expected.

Thanks for the reply and the extended explanation!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms