Player.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using UnityEngine;
  2. namespace Mirror.Examples.SyncDir // ".SyncDirection" would overshadow the enum
  3. {
  4. public class Player : NetworkBehaviour
  5. {
  6. public TextMesh textMesh;
  7. [SyncVar] public int health;
  8. void Update()
  9. {
  10. // show health for everyone
  11. textMesh.text = health.ToString();
  12. // space bar increases health for local player.
  13. // note that trusting the client is a bad idea, especially with health.
  14. // SyncDirection is usually used for movement.
  15. //
  16. // when using custom OnSerialize, the custom OnDeserialize can still
  17. // safely validate client data (check position, velocity etc.).
  18. // this is why it's named SyncDirection, and not ClientAuthority.
  19. // because the server can still validate the client's data first.
  20. //
  21. // try to change SyncDirection to ServerToClient in the editor.
  22. // then restart the game, clients won't be allowed to change their
  23. // own health anymore.
  24. if (isLocalPlayer)
  25. {
  26. if (Input.GetKeyDown(KeyCode.Space))
  27. ++health;
  28. }
  29. }
  30. // show instructions
  31. void OnGUI()
  32. {
  33. if (!isLocalPlayer) return;
  34. int width = 250;
  35. int height = 20;
  36. GUI.Label(
  37. new Rect(Screen.width / 2 - width / 2, Screen.height / 2 - height / 2, width, height),
  38. "Press Space to increase your own health!");
  39. }
  40. }
  41. }