- Home /
Custom classes having a strange behaviour
Hello,
I have two variables of type "PlayerControls"
[System.Serializable]
public class PlayerControls
{
public float horizontal;
public float vertical;
public bool down;
public bool up;
public bool left;
public bool right;
public bool boost;
public bool interact;
public bool jump;
public bool start;
}
And after doing that :
void Start () {
gm.prevInputs = gm.inputs;
}
The variable "prevInputs" keeps being synchronised with the "inputs" variable, what am I doing wrong ?
What do you mean by keeps being synchronized? You're clearly assigning gm.inputs into gm.prevInputs , so I'm not understanding what you're expecting to happen and what's wrong.
Answer by Wasplay · May 08, 2018 at 09:28 PM
It's working ! Thank you so much ! Here is what i've done :
if (buffer)
{
GetInput(gm.buffer1);
buffer = false;
gm.inputs = gm.buffer1;
gm.prevInputs = gm.buffer2;
}
else
{
GetInput(gm.buffer2);
buffer = true;
gm.inputs = gm.buffer2;
gm.prevInputs = gm.buffer1;
}
Answer by MacDx · May 08, 2018 at 05:22 PM
Hmmm I think I know what you're having trouble with now.
Do you know the difference between value types and reference types?
Value types are types (like int,floats,enums,structs, etc.) that when you assign them to a field/variable or pass them to methods, their value will get copied, so if you modify them nothing will happen to the original.
On the other hand, reference types (any class type) will not get copied when you pass them to a method or assign them to variables, instead, you are simply passing a reference so anyone that has that reference will modify the same object.
I'm not sure if my explanation was clear enough so here's a link that provides further detail. http://net-informations.com/faq/general/valuetype-referencetype.htm
So what you're calling strange "synchronization" behaviour is just the normal behaviour of the C# language (and many other modern programming languages). If you just don't want this to happen, you will have to change your PlayerControls class into a struct like this:
[System.Serializable]
public struct PlayerControls //Structs are value types
{
public float horizontal;
public float vertical;
public bool down;
public bool up;
public bool left;
public bool right;
public bool boost;
public bool interact;
public bool jump;
public bool start;
}
Hope this helps!
Same problem :/ I've changed the class to struct but prevInputs = inputs; at start still results in a synchronisation between the two PlayerControls :(
No, that's impossible. You either did not save your changes or you actually have such a copy line somewhere else in Update.
I'm uploading a short video to show you the project, I did everything correctly idk why this isn't working :(