You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.4 KiB

  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.Networking;
  4. namespace Networking.Client
  5. {
  6. [CreateAssetMenu(menuName = "Major Project/Networking/Client/OtherClientsList", order = 150)]
  7. public class ConnectedClients : ScriptableObject
  8. {
  9. #if UNITY_EDITOR
  10. [SerializeField]
  11. [Multiline]
  12. private string DevNotes;
  13. #endif
  14. /// <summary>
  15. /// All Clients which are Currently Connected;
  16. /// </summary>
  17. [SerializeField]
  18. public List<ClientData> AllClients;
  19. /// <summary>
  20. /// Called when a client connects or disconnet
  21. /// </summary>
  22. public System.Action<List<ClientData>> OnClientsChange;
  23. public void SetUp(ClientObject client)
  24. {
  25. Reset();
  26. client.client.RegisterHandler(LoginProtocols.OtherClientConnected, OnClientConnect);
  27. client.client.RegisterHandler(LoginProtocols.OtherClientDisconnected, OnClientDisconnect);
  28. }
  29. public void Reset()
  30. {
  31. AllClients = new List<ClientData>();
  32. OnClientsChange?.Invoke(AllClients);
  33. }
  34. public void OnClientConnect(NetworkMessage msg)
  35. {
  36. LoginProtocols.LoginMsg loginMsg;
  37. if (!msg.TryRead(out loginMsg))
  38. return;
  39. AllClients.Add(new ClientData(loginMsg));
  40. OnClientsChange?.Invoke(AllClients);
  41. }
  42. public void OnClientDisconnect(NetworkMessage msg)
  43. {
  44. LoginProtocols.LoginMsg loginMsg;
  45. if (!msg.TryRead(out loginMsg))
  46. return;
  47. AllClients.RemoveAll(p => (p.Name == loginMsg.Name) && (p.Color == loginMsg.Color) && (p.characterAnimal == loginMsg.Animal));
  48. OnClientsChange?.Invoke(AllClients);
  49. }
  50. }
  51. [System.Serializable]
  52. public class ClientData
  53. {
  54. /// <summary>
  55. /// Client Name
  56. /// </summary>
  57. public string Name;
  58. /// <summary>
  59. /// Color which represents player, picked by player
  60. /// </summary>
  61. public Color Color;
  62. /// <summary>
  63. /// Clients character animal - needed for instantiation
  64. /// </summary>
  65. public string characterAnimal = "Bear";
  66. public ClientData(LoginProtocols.LoginMsg msg)
  67. {
  68. this.Name = msg.Name;
  69. this.Color = msg.Color;
  70. this.characterAnimal = msg.Animal;
  71. }
  72. }
  73. }