Player.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. public Color localColor = Color.white;
  8. [SyncVar] public int health;
  9. readonly SyncList<int> list = new SyncList<int>();
  10. public override void OnStartLocalPlayer()
  11. {
  12. textMesh.color = localColor;
  13. }
  14. void Update()
  15. {
  16. // show health and list for everyone
  17. textMesh.text = $"{health} / {list.Count}";
  18. // key presses increase health / list for local player.
  19. // note that trusting the client is a bad idea, especially with health.
  20. // SyncDirection is usually used for movement.
  21. //
  22. // when using custom OnSerialize, the custom OnDeserialize can still
  23. // safely validate client data (check position, velocity etc.).
  24. // this is why it's named SyncDirection, and not ClientAuthority.
  25. // because the server can still validate the client's data first.
  26. //
  27. // try to change SyncDirection to ServerToClient in the editor.
  28. // then restart the game, clients won't be allowed to change their
  29. // own health anymore.
  30. if (isLocalPlayer)
  31. {
  32. if (Input.GetKeyDown(KeyCode.Space))
  33. ++health;
  34. if (Input.GetKeyDown(KeyCode.L))
  35. list.Add(list.Count);
  36. }
  37. }
  38. // show instructions
  39. void OnGUI()
  40. {
  41. if (!isLocalPlayer) return;
  42. int width = 250;
  43. int height = 50;
  44. GUI.color = localColor;
  45. GUI.Label(
  46. new Rect(Screen.width / 2 - width / 2, Screen.height / 2 - height / 2, width, height),
  47. "Press Space to increase your own health!\nPress L to add to your SyncList!");
  48. }
  49. }
  50. }