Hi,
I’m sorry I know this was post many time but I still don’t understand how it’s working.
I have a game where a client host the game and the others join it.
I want to syncronise a variable between the clients and the server.
I just want something like that:
variable++;
// Whatever if I increase the variable from the client or the server, I want the variable to be increased for everyone.
I saw that there was the SyncVar attribut, but it’s working from the server to the client, but not from a client to the server (and all the others clients) so I can’t use it :/.
How can I do to increase my variable for everyone ?
Thanks in advance,
You are correct, you use SyncVar so that changes to that variable on the server also occur on all client copies of that GameObject. If a client needs to change that variable, the client would run a command, which runs the called method on the server, and on the server you update the value. Note that you can only run commands from a client if that object is either that client’s Player object or if that client has authority over the object.
Simple example:
[SyncVar]
public int MyInt = 0;
public void SetMyIntFromClient(int newMyInt)
{
CmdSetMyInt(newMyInt);
}
[Command]
void CmdSetMyInt(int newMyInt)
{
MyInt = newMyInt;
}
So on the client you would call SetMyIntFromClient and supply it with the new int value, it will call that command, and then the command will update the value on the server. Once that happens then MyInt will update to the new value on all clients, including the client that called the command.
Thanks for your answer, but how can I give authority to a client ?
There is a little check box “Local Player Authority” but it doesn’t change anything.
(It’s working well from the server, but it’s not working from a client, and I have the folowing warning:
Trying to send command for object without authority.)
So this method should do that from the server, but I think that’s only going to work for one player at a time. You could look into messages, which any client could send to the server when they want to affect that variable:
Alternatively, they could call a command on their player object (which they usually already have authority for) and then on the server that method shouts over to your centralised object/component.