1. using UnityEngine;
    2. using UnityEngine.Networking;
    3. using UnityEngine.Networking.Match;
    4. using System.Collections.Generic;
    5. public class HostGame : MonoBehaviour
    6. {
    7. List<MatchInfoSnapshot> matchList = new List<MatchInfoSnapshot>();
    8. bool matchCreated;
    9. NetworkMatch networkMatch;
    10. void Awake()
    11. {
    12. networkMatch = gameObject.AddComponent<NetworkMatch>();
    13. }
    14. void OnGUI()
    15. {
    16. // You would normally not join a match you created yourself but this is possible here for demonstration purposes.
    17. if (GUILayout.Button("Create Room"))
    18. {
    19. string matchName = "room";
    20. uint matchSize = 4;
    21. bool matchAdvertise = true;
    22. string matchPassword = "";
    23. networkMatch.CreateMatch(matchName, matchSize, matchAdvertise, matchPassword, "", "", 0, 0, OnMatchCreate);
    24. }
    25. if (GUILayout.Button("List rooms"))
    26. {
    27. networkMatch.ListMatches(0, 20, "", true, 0, 0, OnMatchList);
    28. if (matchList.Count > 0)
    29. {
    30. GUILayout.Label("Current rooms");
    31. }
    32. foreach (var match in matchList)
    33. {
    34. if (GUILayout.Button(match.name))
    35. {
    36. networkMatch.JoinMatch(match.networkId, "", "", "", 0, 0, OnMatchJoined);
    37. }
    38. }
    39. }
    40. public void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
    41. {
    42. if (success)
    43. {
    44. Debug.Log("Create match succeeded");
    45. matchCreated = true;
    46. NetworkServer.Listen(matchInfo, 9000);
    47. Utility.SetAccessTokenForNetwork(matchInfo.networkId, matchInfo.accessToken);
    48. }
    49. else
    50. {
    51. Debug.LogError("Create match failed: " + extendedInfo);
    52. }
    53. }
    54. public void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
    55. {
    56. networkMatch.JoinMatch(matches[0].networkId, "", "", "", 0, 0, OnMatchJoined);
    57. }
    58. else if (!success)
    59. {
    60. Debug.LogError("List match failed: " + extendedInfo);
    61. }
    62. }
    63. public void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
    64. {
    65. if (success)
    66. {
    67. Debug.Log("Join match succeeded");
    68. if (matchCreated)
    69. {
    70. Debug.LogWarning("Match already set up, aborting...");
    71. return;
    72. }
    73. Utility.SetAccessTokenForNetwork(matchInfo.networkId, matchInfo.accessToken);
    74. NetworkClient myClient = new NetworkClient();
    75. myClient.RegisterHandler(MsgType.Connect, OnConnected);
    76. myClient.Connect(matchInfo);
    77. }
    78. else
    79. {
    80. Debug.LogError("Join match failed " + extendedInfo);
    81. }
    82. }
    83. public void OnConnected(NetworkMessage msg)
    84. {
    85. Debug.Log("Connected!");
    86. }