SocketPlayer.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using UnityEngine.SceneManagement;
  7. /* Socket组件-玩家PK */
  8. public class SocketPlayer : JC.SocketIO.SocketIOClient
  9. {
  10. public static SocketPlayer ins;
  11. public static SocketPlayer NewInstance() {
  12. return new GameObject("SocketPlayer").AddComponent<SocketPlayer>();
  13. }
  14. void Awake()
  15. {
  16. ins = this;
  17. }
  18. public override void OnDestroy()
  19. {
  20. if (ins == this) ins = null;
  21. base.OnDestroy();
  22. }
  23. void Start()
  24. {
  25. connectServer(CommonConfig.gamePKServerWsURL);
  26. }
  27. public override void onLoad()
  28. {
  29. Debug.Log("onLoad");
  30. RequestEnterRoom();
  31. }
  32. public override void onReload()
  33. {
  34. Debug.Log("onReload");
  35. }
  36. public override void onDestroy()
  37. {
  38. Debug.Log("onDestroy");
  39. if (OnlinePKTest.isOpen) {
  40. return;
  41. }
  42. if (!isGameOver) {
  43. PopupMgr.ins.ShowBGTip(TextAutoLanguage2.GetTextByCNKey("某方退出或掉线,联机游戏终止!"));
  44. SceneManager.LoadScene("Home", LoadSceneMode.Single);
  45. }
  46. }
  47. public override void onMiss()
  48. {
  49. Debug.Log("onMiss");
  50. }
  51. //请求加入房间
  52. public void RequestEnterRoom() {
  53. call("RequestEnterRoom", OnlinePKTest.isOpen ? "test" : GlobalData.roomKey);
  54. }
  55. //房间准备完毕,即房间内的玩家都准备好了,接到该通知就可以开始游戏啦
  56. public Action onRoomReadyComplete;
  57. public void OnRoomReadyComplete(int playerIndexInRoom) {
  58. Debug.Log("OnRoomReadyComplete" + ", playerIndexInRoom: " + playerIndexInRoom);
  59. if (OnlinePKTest.isOpen) {
  60. GlobalData.matchPlayerInfos = new List<MatchPlayerInfo>();
  61. MatchPlayerInfo p1 = new MatchPlayerInfo();
  62. p1.nickname = "玩家1";
  63. p1.avatarID = 10;
  64. GlobalData.matchPlayerInfos.Add(p1);
  65. MatchPlayerInfo p2 = new MatchPlayerInfo();
  66. p2.nickname = "玩家2";
  67. p2.avatarID = 20;
  68. GlobalData.matchPlayerInfos.Add(p2);
  69. GlobalData.playerIndexInRoom = playerIndexInRoom;
  70. }
  71. onRoomReadyComplete?.Invoke();
  72. }
  73. //上传游戏数据
  74. public void UploadPKGameData(string key, object data) {
  75. if (!isValid) return;
  76. call("UploadPKGameData", key, data);
  77. }
  78. public Action<string, string> onReceivePKGameData;
  79. public void OnReceivePKGameData(string key, string data) {
  80. onReceivePKGameData?.Invoke(key, data);
  81. }
  82. [NonSerialized] public bool isGameOver = false;
  83. }