PeerList.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace KairoEngine.Multiplayer
  5. {
  6. public class PeerList : MonoBehaviour
  7. {
  8. public ClientBehaviour client;
  9. public List<ClientData> peers;
  10. private void OnEnable()
  11. {
  12. NetMsgEvents.StartListening($"{client.eventStreamName}_PeerConnected", OnPeerConnect);
  13. NetMsgEvents.StartListening($"{client.eventStreamName}_PeerDisconnected", OnPeerDisconnect);
  14. }
  15. private void OnDisable()
  16. {
  17. NetMsgEvents.StopListening($"{client.eventStreamName}_PeerConnected", OnPeerConnect);
  18. NetMsgEvents.StopListening($"{client.eventStreamName}_PeerDisconnected", OnPeerDisconnect);
  19. }
  20. private void OnPeerConnect(string text, int clientId, uint code, NetMsg netMsg)
  21. {
  22. NetClientConnectedMsg msg = (NetClientConnectedMsg)netMsg;
  23. for (int i = 0; i < peers.Count; i++)
  24. {
  25. if(peers[i].playerName == msg.playerName)
  26. {
  27. return;
  28. }
  29. }
  30. if(msg.playerName == client.playerName) return;
  31. peers.Add(new ClientData(-1, msg.playerName, true));
  32. }
  33. private void OnPeerDisconnect(string text, int clientId, uint code, NetMsg netMsg)
  34. {
  35. NetClientDisconnectedMsg msg = (NetClientDisconnectedMsg)netMsg;
  36. for (int i = 0; i < peers.Count; i++)
  37. {
  38. if(peers[i].playerName == msg.playerName)
  39. {
  40. peers.RemoveAt(i);
  41. return;
  42. }
  43. }
  44. }
  45. }
  46. }