- Home /
Syncing variables between two objects of same script
I have a case that i need to sync changes to variables in two objects of same class. When a change happen to one it changes the other. i thought of making a public property for every variable and adding an action within it's Set part to set the private variable for both objects whenever i call a change for the public property. something like this
private bool _connected;
public bool Connected{
get => _connected;
set{_connected = value;
OnConnected?.Invoke(value);
}
}
BUT i think there is something easier and i don't know where to look.
Answer by VoidPhoenix96 · Feb 15, 2021 at 02:35 AM
In one script just write TheFirstVariable = OtherScript.TheSecondVariable
And in the other, TheSecond Variable = script.TheFirstVariable
Make sure to put these lines in Update()
Keep in mind that this will only work on runtime.
Sorry i was not clear, I need to sync same variable in the same scrupt between two objects. If if any changes occurs to one of them if directly changes the other
Do you have a script that would start the action of syncing variables? If so, you can just get the script on both objects and set the variable to the same thing. Like this: Object1.GetComponent().VariableToSync = Number: Object2.GetComponent().VariableToSync = Number;
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
XML Data binding in unity 5 using c# 0 Answers