- Home /
strange cloning array beviour
had a strange thing happen in Unity 18.1.6f1 two int arrays seemed to be duplicates of each other and when accessing the first the second would also update with the same ints even though i never set it directly, this ISN'T the behaviour I was expecting, is this normal?
public int[] playerCoords = { 0, 1 };
public int[] playerCoordsInit = { 0, 1 };
void Start()
{
playerCoords = playerCoordsInit;
}
I got around this by changing to the following:
void Start()
{
playerCoords[0] = playerCoordsInit[0];
playerCoords[1] = playerCoordsInit[1];
}
Literally no idea why It would be doing this?!
Answer by sarahnorthway · Jul 11, 2019 at 08:08 PM
Arrays are a Reference Type in C# and behave like an Object when you set them or pass them into a method.
You aren't making a copy of playerCoordsInit when you do playerCoords = playerCoordsInit
, you just now have 2 ways to reference the same object, so if you change one they both change.
Int, bool and string are Value Types, meaning int X = Y
will put a copy of the value of Y into X. So playerCoords[0] = playerCoordsInit[0]
works as you expect because they're ints.
Your answer
Follow this Question
Related Questions
Converting a string to an int 2 Answers
How to destroy the first clone of a UI Image using an array every time I press a button? 1 Answer
I want some ints stored in a new int right after eachother 1 Answer
Monodevelop is expecting int from my float array 3 Answers
Trying to Instantiate() an object without cloning the code 2 Answers