I have been stuck on a problem for days on sync var hooks. I am working on displaying a player name over the players head, and I will be looking to be able to set a player colour too in the future. Here is my code.
First the sync var:
[SyncVar(hook = "OnNameChanged")] public string playerName = "";
SyncVars only propagate to the other clients automatically if they’re changed on the server, so when a client connects you need to send the server the name it wants to use and then the server can set the SyncVar so all the other clients get it.
Actually, I tried it out on my brother’s computer but we encountered that player names do not work on two computers but only on 2 instances running on the same computer. I suspect its something to do with player prefs. How can I fix this?
Honestly that would require a lot more info about how you have the rest of your game setup. I should note that in your example above you hard-code the name in the code itself, which would mean that all players have the same name… Good luck!
I switched it so you can set your own name using an input field, and saves to player prefs. If I posted my entire script that has everything to do with the name on it, would you might be able to figure it out?
I highly suggest doing some sequence diagrams to understand the flow of messages between the Server and Client. https://www.planttext.com or https://www.websequencediagrams.com are great online tools for creating these diagrams which have really helped me understand why things were happening and when. Also reading the source code to the UNET HLAPI - while a bummer that this is necessary, it will help you immeasurably with groking what is going on. And rereading the whole Networking section of the Unity docs. Simplifying a test case/example project is also good - what is the simplest thing i can get working, with 1 syncvar, so i know that i actually understand what is happening, or at least have working code to build on. These are all the things i do when i get stuck on some bit of networking. Good Luck!