I’m having a hard time setting up SyncVars and Command functions. I don’t quite understand the flow of how this is supposed to work.
From what I gather, and please correct me at any point if I am wrong, when a variable is tagged [SyncVar], then if it changes on the server, clients should see it changed.
Clients can’t directly change SyncVars. Only the Server can. So if you want a Client to update a SyncVar, you have to use Command attribute on a function. Command functions, tagged with [Command] and the function name starting with Cmd, are functions that when called are executed by the server. So if you want to tell the server, from a client, to change a SyncVar variable, you need to use a Command function, that way the server changes the variable, and then the change will be seen on the clients.
For some reason I can not get a client to tell the server to change a SyncVar.
Am I supposed to tag the server controlled object with a server identity and check Server Only?
Am I supposed attach a client network identity component to the UI Canvas GameObject that has the script I want the players to use?
Does the client authority object get the Cmd function or do I put that on the Server Authority object’s script?
Right now I have 2 scripts:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
public class Stats : NetworkBehaviour
{
public const int maxHealth = 100;
public Text healthText;
[SyncVar(hook = "OnChangeHealth")]
public int currentHealth = maxHealth;
public void TakeDamage(int amount)
{
if (!isServer)
return;
currentHealth -= amount;
}
void OnChangeHealth(int health)
{
currentHealth = health;
}
}
and
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class playerHUDController : NetworkBehaviour {
public Button basicButton;
public Stats statObject;
void Start () {
}
void Update () {
statObject.healthText.text = statObject.currentHealth.ToString();
}
public void OnBasicButtonSelect()
{
statObject.TakeDamage(10);
}
}
When I am on the Host/Client version of the game, I can press the button, and I see the Text on my screen change: 100, 90, 80, etc.
On a separate execution of the game, I connect as client only, and I can see the changes being made from the Host/Client game when I click the button on the host/client.
But if I click the button on the client only game, nothing happens. Nothing changes on the screen, and the Host/Client game doesn’t change either.
What am I doing wrong here? It works perfectly on the Host/Client, but on client it does nothing.
Any assistance would be great. Thank you!