Games









How do I use Games
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: NamePickGui.cs Copy
38     public void OnGUI()
39     {
40         // Enter-Key handling:
41         if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return))
42         {
43             if (!string.IsNullOrEmpty(this.InputLine))
44             {
45                 this.StartChat();
46                 return;
47             }
48         }
49
50
51         GUI.skin.label.wordWrap = true;
52         GUILayout.BeginArea(guiCenteredRect);
53
54
55         if (this.chatComponent != null && string.IsNullOrEmpty(this.chatComponent.ChatAppId))
56         {
57             GUILayout.Label("To continue, configure your Chat AppId.\nIt's listed in the Chat Dashboard (online).\nStop play-mode and edit:\nScripts/ChatGUI in the Hierarchy.");
58             if (GUILayout.Button("Open Chat Dashboard"))
59             {
60                 Application.OpenURL("https://www.exitgames.com/en/Chat/Dashboard");
61             }
62             GUILayout.EndArea();
63             return;
64         }
65
66         GUILayout.Label(this.helpText);
67
68         GUILayout.BeginHorizontal();
69         GUI.SetNextControlName("NameInput");
70         this.InputLine = GUILayout.TextField(this.InputLine);
71         if (GUILayout.Button("Connect", GUILayout.ExpandWidth(false)))
72         {
73             this.StartChat();
74         }
75         GUILayout.EndHorizontal();
76
77         GUILayout.EndArea();
78
79
80         GUI.FocusControl("NameInput");
81     }
File name: GUICustomAuth.cs Copy
81     void OnGUI()
82     {
83         if (PhotonNetwork.connected)
84         {
85             GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
86             return;
87         }
88
89
90         GUILayout.BeginArea(GuiRect);
91         switch (guiState)
92         {
93             case GuiState.AuthFailed:
94                 GUILayout.Label("Authentication Failed");
95
96                 GUILayout.Space(10);
97
98                 GUILayout.Label("Error message:\n'" + this.authDebugMessage + "'");
99
100                 GUILayout.Space(10);
101
102                 GUILayout.Label("For this demo set the Authentication URL in the Dashboard to:\nhttp://photon.webscript.io/auth-demo-equals");
103                 GUILayout.Label("That authentication-service has no user-database. It confirms any user if 'name equals password'.");
104                 GUILayout.Label("The error message comes from that service and can be customized.");
105
106                 GUILayout.Space(10);
107
108                 GUILayout.BeginHorizontal();
109                 if (GUILayout.Button("Back"))
110                 {
111                     SetStateAuthInput();
112                 }
113                 if (GUILayout.Button("Help"))
114                 {
115                     SetStateAuthHelp();
116                 }
117                 GUILayout.EndHorizontal();
118                 break;
119
120             case GuiState.AuthHelp:
121
122                 GUILayout.Label("By default, any player can connect to Photon.\n'Custom Authentication' can be enabled to reject players without valid user-account.");
123
124                 GUILayout.Label("The actual authentication must be done by a web-service which you host and customize. Example sourcecode for these services is available on the docs page.");
125
126                 GUILayout.Label("For this demo set the Authentication URL in the Dashboard to:\nhttp://photon.webscript.io/auth-demo-equals");
127                 GUILayout.Label("That authentication-service has no user-database. It confirms any user if 'name equals password'.");
128
129                 GUILayout.Space(10);
130                 if (GUILayout.Button("Configure Authentication (Dashboard)"))
131                 {
132                     Application.OpenURL("https://cloud.exitgames.com/dashboard");
133                 }
134                 if (GUILayout.Button("Authentication Docs"))
135                 {
136                     Application.OpenURL("https://doc.exitgames.com/en/pun/current/tutorials/pun-and-facebook-custom-authentication");
137                 }
138
139
140                 GUILayout.Space(10);
141                 if (GUILayout.Button("Back to input"))
142                 {
143                     SetStateAuthInput();
144                 }
145                 break;
146
147             case GuiState.AuthInput:
148
149                 GUILayout.Label("Authenticate yourself");
150
151                 GUILayout.BeginHorizontal();
152                 this.authName = GUILayout.TextField(this.authName, GUILayout.Width(Screen.width/4 - 5));
153                 GUILayout.FlexibleSpace();
154                 this.authToken = GUILayout.TextField(this.authToken, GUILayout.Width(Screen.width/4 - 5));
155                 GUILayout.EndHorizontal();
156
157
158                 if (GUILayout.Button("Authenticate"))
159                 {
160                     PhotonNetwork.AuthValues = new AuthenticationValues();
161                     PhotonNetwork.AuthValues.SetAuthParameters(this.authName, this.authToken);
162                     PhotonNetwork.ConnectUsingSettings("1.0");
163                 }
164
165                 GUILayout.Space(10);
166
167                 if (GUILayout.Button("Help", GUILayout.Width(100)))
168                 {
169                     SetStateAuthHelp();
170                 }
171
172                 break;
173         }
174
175         GUILayout.EndArea();
176     }
File name: WorkerMenu.cs Copy
65     public void OnGUI()
66     {
67         if (this.Skin != null)
68         {
69             GUI.skin = this.Skin;
70         }
71
72         if (!PhotonNetwork.connected)
73         {
74             if (PhotonNetwork.connecting)
75             {
76                 GUILayout.Label("Connecting to: " + PhotonNetwork.ServerAddress);
77             }
78             else
79             {
80                 GUILayout.Label("Not connected. Check console output. Detailed connection state: " + PhotonNetwork.connectionStateDetailed + " Server: " + PhotonNetwork.ServerAddress);
81             }
82
83             if (this.connectFailed)
84             {
85                 GUILayout.Label("Connection failed. Check setup and use Setup Wizard to fix configuration.");
86                 GUILayout.Label(String.Format("Server: {0}", new object[] {PhotonNetwork.ServerAddress}));
87                 GUILayout.Label("AppId: " + PhotonNetwork.PhotonServerSettings.AppID);
88
89                 if (GUILayout.Button("Try Again", GUILayout.Width(100)))
90                 {
91                     this.connectFailed = false;
92                     PhotonNetwork.ConnectUsingSettings("0.9");
93                 }
94             }
95
96             return;
97         }
98
99         Rect content = new Rect((Screen.width - WidthAndHeight.x)/2, (Screen.height - WidthAndHeight.y)/2, WidthAndHeight.x, WidthAndHeight.y);
100         GUI.Box(content,"Join or Create Room");
101         GUILayout.BeginArea(content);
102
103         GUILayout.Space(40);
104
105         // Player name
106         GUILayout.BeginHorizontal();
107         GUILayout.Label("Player name:", GUILayout.Width(150));
108         PhotonNetwork.playerName = GUILayout.TextField(PhotonNetwork.playerName);
109         GUILayout.Space(158);
110         if (GUI.changed)
111         {
112             // Save name
113             PlayerPrefs.SetString("playerName", PhotonNetwork.playerName);
114         }
115         GUILayout.EndHorizontal();
116
117         GUILayout.Space(15);
118
119         // Join room by title
120         GUILayout.BeginHorizontal();
121         GUILayout.Label("Roomname:", GUILayout.Width(150));
122         this.roomName = GUILayout.TextField(this.roomName);
123
124         if (GUILayout.Button("Create Room", GUILayout.Width(150)))
125         {
126             PhotonNetwork.CreateRoom(this.roomName, new RoomOptions() { maxPlayers = 10 }, null);
127         }
128
129         GUILayout.EndHorizontal();
130
131         // Create a room (fails if exist!)
132         GUILayout.BeginHorizontal();
133         GUILayout.FlexibleSpace();
134         //this.roomName = GUILayout.TextField(this.roomName);
135         if (GUILayout.Button("Join Room", GUILayout.Width(150)))
136         {
137             PhotonNetwork.JoinRoom(this.roomName);
138         }
139
140         GUILayout.EndHorizontal();
141
142
143         if (!string.IsNullOrEmpty(this.ErrorDialog))
144         {
145             GUILayout.Label(this.ErrorDialog);
146
147             if (timeToClearDialog < Time.time)
148             {
149                 timeToClearDialog = 0;
150                 this.ErrorDialog = "";
151             }
152         }
153
154         GUILayout.Space(15);
155
156         // Join random room
157         GUILayout.BeginHorizontal();
158
159         GUILayout.Label(PhotonNetwork.countOfPlayers + " users are online in " + PhotonNetwork.countOfRooms + " rooms.");
160         GUILayout.FlexibleSpace();
161         if (GUILayout.Button("Join Random", GUILayout.Width(150)))
162         {
163             PhotonNetwork.JoinRandomRoom();
164         }
165
166
167         GUILayout.EndHorizontal();
168
169         GUILayout.Space(15);
170         if (PhotonNetwork.GetRoomList().Length == 0)
171         {
172             GUILayout.Label("Currently no games are available.");
173             GUILayout.Label("Rooms will be listed here, when they become available.");
174         }
175         else
176         {
177             GUILayout.Label(PhotonNetwork.GetRoomList().Length + " rooms available:");
178
179             // Room listing: simply call GetRoomList: no need to fetch/poll whatever!
180             this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
181             foreach (RoomInfo roomInfo in PhotonNetwork.GetRoomList())
182             {
183                 GUILayout.BeginHorizontal();
184                 GUILayout.Label(roomInfo.name + " " + roomInfo.playerCount + "/" + roomInfo.maxPlayers);
185                 if (GUILayout.Button("Join", GUILayout.Width(150)))
186                 {
187                     PhotonNetwork.JoinRoom(roomInfo.name);
188                 }
189
190                 GUILayout.EndHorizontal();
191             }
192
193             GUILayout.EndScrollView();
194         }
195
196         GUILayout.EndArea();
197     }
File name: LoadbalancingPeer.cs Copy
86         public virtual bool OpCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby lobby, Hashtable playerProperties, bool onGameServer)
87         {
88             if (this.DebugOut >= DebugLevel.INFO)
89             {
90                 this.Listener.DebugReturn(DebugLevel.INFO, "OpCreateRoom()");
91             }
92
93             Dictionary op = new Dictionary();
94
95             if (!string.IsNullOrEmpty(roomName))
96             {
97                 op[ParameterCode.RoomName] = roomName;
98             }
99             if (lobby != null)
100             {
101                 op[ParameterCode.LobbyName] = lobby.Name;
102                 op[ParameterCode.LobbyType] = (byte)lobby.Type;
103             }
104
105             if (onGameServer)
106             {
107                 if (playerProperties != null && playerProperties.Count > 0)
108                 {
109                     op[ParameterCode.PlayerProperties] = playerProperties;
110                     op[ParameterCode.Broadcast] = true; // TODO: check if this also makes sense when creating a room?! // broadcast actor properties
111                 }
112
113
114                 if (roomOptions == null)
115                 {
116                     roomOptions = new RoomOptions();
117                 }
118
119                 Hashtable gameProperties = new Hashtable();
120                 op[ParameterCode.GameProperties] = gameProperties;
121                 gameProperties.MergeStringKeys(roomOptions.customRoomProperties);
122
123                 gameProperties[GameProperties.IsOpen] = roomOptions.isOpen; // TODO: check default value. dont send this then
124                 gameProperties[GameProperties.IsVisible] = roomOptions.isVisible; // TODO: check default value. dont send this then
125                 gameProperties[GameProperties.PropsListedInLobby] = roomOptions.customRoomPropertiesForLobby;
126                 if (roomOptions.maxPlayers > 0)
127                 {
128                     gameProperties[GameProperties.MaxPlayers] = roomOptions.maxPlayers;
129                 }
130                 if (roomOptions.cleanupCacheOnLeave)
131                 {
132                     op[ParameterCode.CleanupCacheOnLeave] = true; // this is actually setting the room's config
133                     gameProperties[GameProperties.CleanupCacheOnLeave] = true; // this is only informational for the clients which join
134                 }
135             }
136
137             // UnityEngine.Debug.Log("CreateGame: " + SupportClass.DictionaryToString(op));
138             return this.OpCustom(OperationCode.CreateGame, op, true);
139         }
File name: LoadbalancingPeer.cs Copy
143         public virtual bool OpJoinRoom(string roomName, RoomOptions roomOptions, TypedLobby lobby, bool createIfNotExists, Hashtable playerProperties, bool onGameServer)
144         {
145             Dictionary op = new Dictionary();
146
147             if (!string.IsNullOrEmpty(roomName))
148             {
149                 op[ParameterCode.RoomName] = roomName;
150             }
151             if (createIfNotExists)
152             {
153                 op[ParameterCode.CreateIfNotExists] = true;
154                 if (lobby != null)
155                 {
156                     op[ParameterCode.LobbyName] = lobby.Name;
157                     op[ParameterCode.LobbyType] = (byte)lobby.Type;
158                 }
159             }
160
161             if (onGameServer)
162             {
163                 if (playerProperties != null && playerProperties.Count > 0)
164                 {
165                     op[ParameterCode.PlayerProperties] = playerProperties;
166                     op[ParameterCode.Broadcast] = true; // broadcast actor properties
167                 }
168
169
170                 if (createIfNotExists)
171                 {
172                     if (roomOptions == null)
173                     {
174                         roomOptions = new RoomOptions();
175                     }
176
177                     Hashtable gameProperties = new Hashtable();
178                     op[ParameterCode.GameProperties] = gameProperties;
179                     gameProperties.MergeStringKeys(roomOptions.customRoomProperties);
180
181                     gameProperties[GameProperties.IsOpen] = roomOptions.isOpen;
182                     gameProperties[GameProperties.IsVisible] = roomOptions.isVisible;
183                     gameProperties[GameProperties.PropsListedInLobby] = roomOptions.customRoomPropertiesForLobby;
184                     if (roomOptions.maxPlayers > 0)
185                     {
186                         gameProperties[GameProperties.MaxPlayers] = roomOptions.maxPlayers;
187                     }
188                     if (roomOptions.cleanupCacheOnLeave)
189                     {
190                         op[ParameterCode.CleanupCacheOnLeave] = true; // this is actually setting the room's config
191                         gameProperties[GameProperties.CleanupCacheOnLeave] = true; // this is only informational for the clients which join
192                     }
193                 }
194             }
195
196             // UnityEngine.Debug.Log("JoinGame: " + SupportClass.DictionaryToString(op));
197             return this.OpCustom(OperationCode.JoinGame, op, true);
198         }
File name: NetworkingPeer.cs Copy
112     public string mGameserver { get; internal set; }
File name: NetworkingPeer.cs Copy
185     public NetworkingPeer(IPhotonPeerListener listener, string playername, ConnectionProtocol connectionProtocol) : base(listener, connectionProtocol)
186     {
187         #if !UNITY_EDITOR && (UNITY_WINRT)
188         // this automatically uses a separate assembly-file with Win8-style Socket usage (not possible in Editor)
189         Debug.LogWarning("Using PingWindowsStore");
190         PhotonHandler.PingImplementation = typeof(PingWindowsStore); // but for ping, we have to set the implementation explicitly to Win 8 Store/Phone
191         #endif
192
193         #pragma warning disable 0162 // the library variant defines if we should use PUN's SocketUdp variant (at all)
194         if (PhotonPeer.NoSocket)
195         {
196             #if !UNITY_EDITOR && (UNITY_PS3 || UNITY_ANDROID)
197             Debug.Log("Using class SocketUdpNativeDynamic");
198             this.SocketImplementation = typeof(SocketUdpNativeDynamic);
199             PhotonHandler.PingImplementation = typeof(PingNativeDynamic);
200             #elif !UNITY_EDITOR && UNITY_IPHONE
201             Debug.Log("Using class SocketUdpNativeStatic");
202             this.SocketImplementation = typeof(SocketUdpNativeStatic);
203             PhotonHandler.PingImplementation = typeof(PingNativeStatic);
204             #elif !UNITY_EDITOR && (UNITY_WINRT)
205             // this automatically uses a separate assembly-file with Win8-style Socket usage (not possible in Editor)
206             #else
207             this.SocketImplementation = typeof (SocketUdp);
208             PhotonHandler.PingImplementation = typeof(PingMonoEditor);
209             #endif
210
211             if (this.SocketImplementation == null)
212             {
213                 Debug.Log("No socket implementation set for 'NoSocket' assembly. Please contact Exit Games.");
214             }
215         }
216         #pragma warning restore 0162
217
218         if (PhotonHandler.PingImplementation == null)
219         {
220             PhotonHandler.PingImplementation = typeof(PingMono);
221         }
222
223         this.Listener = this;
224         this.lobby = TypedLobby.Default;
225         this.LimitOfUnreliableCommands = 40;
226
227         // don't set the field directly! the listener is passed on to other classes, which get updated by the property set method
228         this.externalListener = listener;
229         this.PlayerName = playername;
230         this.mLocalActor = new PhotonPlayer(true, -1, this.playername);
231         this.AddNewPlayer(this.mLocalActor.ID, this.mLocalActor);
232
233         // RPC shortcut lookup creation (from list of RPCs, which is updated by Editor scripts)
234         rpcShortcuts = new Dictionary(PhotonNetwork.PhotonServerSettings.RpcList.Count);
235         for (int index = 0; index < PhotonNetwork.PhotonServerSettings.RpcList.Count; index++)
236         {
237             var name = PhotonNetwork.PhotonServerSettings.RpcList[index];
238             rpcShortcuts[name] = index;
239         }
240
241         this.State = global::PeerState.PeerCreated;
242     }
File name: NetworkingPeer.cs Copy
253     public bool Connect(string serverAddress, ServerConnection type)
254     {
255         if (PhotonHandler.AppQuits)
256         {
257             Debug.LogWarning("Ignoring Connect() because app gets closed. If this is an error, check PhotonHandler.AppQuits.");
258             return false;
259         }
260
261         if (PhotonNetwork.connectionStateDetailed == global::PeerState.Disconnecting)
262         {
263             Debug.LogError("Connect() failed. Can't connect while disconnecting (still). Current state: " + PhotonNetwork.connectionStateDetailed);
264             return false;
265         }
266
267         // connect might fail, if the DNS name can't be resolved or if no network connection is available
268         bool connecting = base.Connect(serverAddress, "");
269         if (connecting)
270         {
271             switch (type)
272             {
273                 case ServerConnection.NameServer:
274                     State = global::PeerState.ConnectingToNameServer;
275                     break;
276                 case ServerConnection.MasterServer:
277                     State = global::PeerState.ConnectingToMasterserver;
278                     break;
279                 case ServerConnection.GameServer:
280                     State = global::PeerState.ConnectingToGameserver;
281                     break;
282             }
283         }
284
285         return connecting;
286     }
File name: NetworkingPeer.cs Copy
419     private void DisconnectToReconnect()
420     {
421         switch (this.server)
422         {
423             case ServerConnection.NameServer:
424                 this.State = global::PeerState.DisconnectingFromNameServer;
425                 base.Disconnect();
426                 break;
427             case ServerConnection.MasterServer:
428                 this.State = global::PeerState.DisconnectingFromMasterserver;
429                 base.Disconnect();
430                 //LeftLobbyCleanup();
431                 break;
432             case ServerConnection.GameServer:
433                 this.State = global::PeerState.DisconnectingFromGameserver;
434                 base.Disconnect();
435                 //this.LeftRoomCleanup();
436                 break;
437         }
438     }
File name: NetworkingPeer.cs Copy
822     private void GameEnteredOnGameServer(OperationResponse operationResponse)
823     {
824         if (operationResponse.ReturnCode != 0)
825         {
826             switch (operationResponse.OperationCode)
827             {
828                 case OperationCode.CreateGame:
829                     if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
830                     {
831                         Debug.Log("Create failed on GameServer. Changing back to MasterServer. Msg: " + operationResponse.DebugMessage);
832                     }
833                     SendMonoMessage(PhotonNetworkingMessage.OnPhotonCreateRoomFailed, operationResponse.ReturnCode, operationResponse.DebugMessage);
834                     break;
835                 case OperationCode.JoinGame:
836                     if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
837                     {
838                         Debug.Log("Join failed on GameServer. Changing back to MasterServer. Msg: " + operationResponse.DebugMessage);
839                         if (operationResponse.ReturnCode == ErrorCode.GameDoesNotExist)
840                         {
841                             Debug.Log("Most likely the game became empty during the switch to GameServer.");
842                         }
843                     }
844                     SendMonoMessage(PhotonNetworkingMessage.OnPhotonJoinRoomFailed, operationResponse.ReturnCode, operationResponse.DebugMessage);
845                     break;
846                 case OperationCode.JoinRandomGame:
847                     if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
848                     {
849                         Debug.Log("Join failed on GameServer. Changing back to MasterServer. Msg: " + operationResponse.DebugMessage);
850                         if (operationResponse.ReturnCode == ErrorCode.GameDoesNotExist)
851                         {
852                             Debug.Log("Most likely the game became empty during the switch to GameServer.");
853                         }
854                     }
855                     SendMonoMessage(PhotonNetworkingMessage.OnPhotonRandomJoinFailed, operationResponse.ReturnCode, operationResponse.DebugMessage);
856                     break;
857             }
858
859             this.DisconnectToReconnect();
860             return;
861         }
862
863         this.State = global::PeerState.Joined;
864         this.mRoomToGetInto.isLocalClientInside = true;
865
866         Hashtable actorProperties = (Hashtable)operationResponse[ParameterCode.PlayerProperties];
867         Hashtable gameProperties = (Hashtable)operationResponse[ParameterCode.GameProperties];
868         this.ReadoutProperties(gameProperties, actorProperties, 0);
869
870         // the local player's actor-properties are not returned in join-result. add this player to the list
871         int localActorNr = (int)operationResponse[ParameterCode.ActorNr];
872
873         this.ChangeLocalID(localActorNr);
874         this.CheckMasterClient(-1);
875
876         if (this.mPlayernameHasToBeUpdated)
877         {
878             this.SendPlayerName();
879         }
880
881         switch (operationResponse.OperationCode)
882         {
883             case OperationCode.CreateGame:
884                 SendMonoMessage(PhotonNetworkingMessage.OnCreatedRoom);
885                 break;
886             case OperationCode.JoinGame:
887             case OperationCode.JoinRandomGame:
888                 // the mono message for this is sent at another place
889                 break;
890         }
891     }

Download file with original file name:Games

Games 153 lượt xem

Gõ tìm kiếm nhanh...