void OnGUI() { GUI.Label(new Rect(Screen.width / 2 - 75, 20, 150, 20), PhotonNetwork.connectionStateDetailed.ToString()); if (GUI.Button(new Rect(Screen.width / 2 - 50, 50, 100, 30), "加入游戏房间")) { if (PhotonNetwork.connected) { PhotonNetwork.JoinOrCreateRoom("xiaogeformax", new RoomOptions { MaxPlayers = 16 }, null); } } if (GUI.Button(new Rect(Screen.width / 2 - 50, 90, 100, 30), "退出游戏房间")) { if (PhotonNetwork.connected) { PhotonNetwork.LeaveRoom(); } } if (GUI.Button(new Rect(Screen.width / 2 - 50, 130, 100, 30), "Connect")) { if (PhotonNetwork.connectionStateDetailed == ClientState.PeerCreated) { PhotonNetwork.ConnectToBestCloudServer("v1.0"); } } }
public override void OnActive() { pv = this.GetComponent <PhotonView>(); //Connect to the main photon server. This is the only IP and port we ever need to set(!) Debug.Log("Connecting to network"); netObject.DoNetworkConnect(); // Capture the "on joined" event netObject.OnNetworkConnect += NetConnected; netObject.OnRoomJoined += JoinedRoom; netObject.OnRoomLeft += LeftRoom; //Load name from PlayerPrefs // Set the room name to the player name roomName = PhotonNetwork.playerName + "'s Room"; Debug.Log("Connecting to PUN"); if (PhotonNetwork.connected == false) { PhotonNetwork.ConnectUsingSettings("0.1"); PhotonNetwork.ConnectToBestCloudServer("0.1"); } }
public void Connect() { // this makes sure we can use PhotonNetwork.LoadLevel() on the master client and all clients in the same room sync their level automatically PhotonNetwork.automaticallySyncScene = false; // the following line checks if this client was just created (and not yet online). if so, we connect if (PhotonNetwork.connectionStateDetailed == PeerState.PeerCreated) { // Connect to the photon master-server. We use the settings saved in PhotonServerSettings (a .asset file in this project) PhotonNetwork.ConnectToBestCloudServer("1.0v"); } if (ConnectInUpdate && AutoConnect && !PhotonNetwork.connected) { Debug.Log("Update() was called by Unity. Scene is loaded. Let's connect to the Photon Master Server. Calling: PhotonNetwork.ConnectUsingSettings();"); ConnectInUpdate = false; PhotonNetwork.ConnectUsingSettings(Version + "." + Application.loadedLevel); } // generate a name for this player, if none is assigned yet /*if (String.IsNullOrEmpty(PhotonNetwork.playerName)) * { * PhotonNetwork.playerName = "Guest" + Random.Range(1, 9999); * } */ // if you wanted more debug out, turn this on: // PhotonNetwork.logLevel = NetworkLogLevel.Full; }
/// <summary> /// Starts initializing and connecting to a game. Depends on the selected network mode. /// Sets the current player name prior to connecting to the servers. /// </summary> public static void StartMatch(NetworkMode mode) { PhotonNetwork.automaticallySyncScene = true; PhotonNetwork.playerName = PlayerPrefs.GetString(PrefsKeys.playerName); switch (mode) { //connects to a cloud game available on the Photon servers case NetworkMode.Online: #if UNITY_WEBGL //best region is not supported on WebGL, choose the location where your server is located, //or implement an option in your game for players to select their preferred location PhotonNetwork.ConnectToRegion(CloudRegionCode.us, appVersion); #else PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.BestRegion; PhotonNetwork.ConnectToBestCloudServer(appVersion); #endif break; //search for open LAN games on the current network, otherwise open a new one case NetworkMode.LAN: PhotonNetwork.ConnectToMaster(PlayerPrefs.GetString(PrefsKeys.serverAddress), 5055, PhotonNetwork.PhotonServerSettings.AppID, appVersion); break; //enable Photon offline mode to not send any network messages at all case NetworkMode.Offline: PhotonNetwork.offlineMode = true; break; } }
IEnumerator OpenRoutine() { if (!InLobby()) { if (PhotonNetwork.connected) { PhotonNetwork.Disconnect(); yield return(null); } PhotonNetwork.autoJoinLobby = true; PhotonNetwork.ConnectToBestCloudServer(NetworkingController.GetPhotonGameVersion()); while (!InLobby()) { // TODO some connecting feedback.. yield return(null); } } Refresh(); // Keep auto-refreshing until we get SOMETHING while (PhotonNetwork.GetRoomList() == null || PhotonNetwork.GetRoomList().Length == 0) { yield return(new WaitForSecondsRealtime(1f)); Refresh(); } }
public void Update() { if (isConnectAllowed && !PhotonNetwork.connected) { CBUG.Log("Beginning Connection . . ."); isConnectAllowed = false; if (PlayerPrefs.GetInt("Server", 0) == 0) { PhotonNetwork.ConnectToBestCloudServer(version); CBUG.Log("Connecting to Best Region."); } else { PhotonNetwork.ConnectToRegion(isEastServer ? CloudRegionCode.us : CloudRegionCode.usw, version); CBUG.Log("Connecting to Chosen Region."); } CBUG.Log("Version Number is: " + version); PhotonNetwork.sendRate = SendRate; PhotonNetwork.sendRateOnSerialize = SendRate; } if (!PhotonNetwork.connectedAndReady && PhotonNetwork.connecting) { printStatus(); } if (!PhotonNetwork.connected) { return; } //if(PhotonNetwork.room != null) // CBUG.Do("TotalRoomPlayersIs: " + PhotonNetwork.room.playerCount); if (Time.time - previousUpdateTime > ServerUpdateLoopTime) { previousUpdateTime = Time.time; setServerStats(); } //CBUG.Log("CHAR NUM: " + ID_to_CharNum[1]); #region Match Tracking if (readyTotal >= PhotonNetwork.playerList.Length && !startTheMatch && !startCountdown) { startTimer = CountdownLength; startCountdown = true; StartCoroutine(GameCountdown()); } if (startCountdown == true && readyTotal < PhotonNetwork.playerList.Length) { startCountdown = false; } #endregion }
private IEnumerator TryReconnect() { if (PhotonNetwork.IsConnected) { yield return(null); } yield return(new WaitForSeconds(1)); Debug.Log("reconnect"); PhotonNetwork.ConnectToBestCloudServer(); }
public virtual void ConnectToBestCloudServer() { isConnectOffline = false; PhotonNetwork.automaticallySyncScene = true; PhotonNetwork.autoJoinLobby = false; PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.BestRegion; PhotonNetwork.offlineMode = false; PhotonNetwork.ConnectToBestCloudServer(gameVersion); if (onConnectingToMaster != null) { onConnectingToMaster.Invoke(); } }
/// <summary> /// Start the connection process. /// - If already connected, we attempt to join a random room. /// - Esle, connect this application instance to Photon Cloud Network /// </summary> public void Connect(string pseudo, string token) { progressLabel.SetActive(true); controlPanel.SetActive(false); // We try to connect to server PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.BestRegion; PhotonNetwork.ConnectToBestCloudServer(GameVersion); // - set up DatabaseRequester DatabaseRequester.SetDBToken(token); DatabaseRequester.GetInstance().PingServer(); DatabaseRequester.SetPseudo(pseudo); }
public void Connect2() { var gameVersion = menuLoaded ? "eddy" + 5 : "1"; PhotonNetwork.PhotonServerSettings.AppID = bs.settings.serv.appIds[appId % bs.settings.serv.appIds.Length]; if (serverRegion == -1) { PhotonNetwork.ConnectToBestCloudServer(gameVersion); } else { PhotonNetwork.ConnectToMaster(ServerSettings.FindServerAddressForRegion(serverRegion), 5055, PhotonNetwork.PhotonServerSettings.AppID, gameVersion); } }
public virtual void ConnectToBestCloudServer() { isConnectOffline = false; // Delete saved best region, to re-ping all regions, to fix unknow ping problem ServerSettings.ResetBestRegionCodeInPreferences(); PhotonNetwork.NetworkingClient.SerializationProtocol = ExitGames.Client.Photon.SerializationProtocol.GpBinaryV18; PhotonNetwork.AutomaticallySyncScene = true; PhotonNetwork.OfflineMode = false; PhotonNetwork.ConnectToBestCloudServer(); isConnectingToBestRegion = true; if (onConnectingToMaster != null) { onConnectingToMaster.Invoke(); } }
// DEFINE O CÓDIGO PARA ENTRAR NA NUVEM -------- // --------------------------------------------- public void setCloud() { codeCloudTemp = inputCodeCloud.GetComponent <Text>().text; if (codeCloudTemp != "") { scriptController.codeCloud = codeCloudTemp; PhotonNetwork.ConnectToBestCloudServer("1.0"); callListLobs(); } else { errorCloud.GetComponent <Text>().text = "Você precisa inserir o código de coexão"; errorCloud.GetComponent <Text>().color = new Color(255, 255, 0, 1); } }
private void GetTokenCallback(GetPhotonAuthenticationTokenResult result) { // Clean errorMessage.text = ""; string photonToken = result.PhotonCustomAuthenticationToken; Debug.Log(string.Format("Yay, logged in in session token: {0}", photonToken)); PhotonNetwork.AuthValues = new AuthenticationValues(); PhotonNetwork.AuthValues.AuthType = CustomAuthenticationType.Custom; PhotonNetwork.AuthValues.AddAuthParameter("username", PlayerPersistentData.playerID); PhotonNetwork.AuthValues.AddAuthParameter("Token", photonToken); PhotonNetwork.ConnectToBestCloudServer("1.0"); PlayFabClientAPI.GetAccountInfo(new GetAccountInfoRequest { }, GetUserData, PlayfabErrorCallback, null); }
void Start() { if (!PhotonNetwork.IsConnectedAndReady) { PhotonNetwork.AutomaticallySyncScene = true; PhotonNetwork.GameVersion = gameVersion; PhotonNetwork.ConnectUsingSettings(); PhotonNetwork.ConnectToBestCloudServer(); //Conéctese a la región de Photon Cloud con el ping más bajo (en plataformas que admiten Ping de Unity). SetPlayerName(NickPlayer); PhotonNetwork.ConnectUsingSettings(); EstablecerRoomOptions(10); } if (PhotonNetwork.IsConnected) { } FriendsList = new List <string>(); }
// EXECUTABLE: ---------------------------------------------------------------------------- public override bool InstantExecute(GameObject target, IAction[] actions, int index, params object[] parameters) { if (!string.IsNullOrEmpty(gameVersion.GetValue(target))) { PhotonNetwork.GameVersion = gameVersion.GetValue(target); } bool result = false; switch (method) { case ConnectType.UsingSettings: result = PhotonNetwork.ConnectUsingSettings(); break; case ConnectType.Region: result = PhotonNetwork.ConnectToRegion(GetRegionCode(region)); break; case ConnectType.BestCloudServer: result = PhotonNetwork.ConnectToBestCloudServer(); break; } return(result); }
public override void OnEnter() { if (connectToBestServer.Value) { #if !(UNITY_WINRT || UNITY_WP8 || UNITY_PS3 || UNITY_WIIU) PhotonNetwork.ConnectToBestCloudServer(gameVersion.Value); #else PhotonNetwork.ConnectUsingSettings(gameVersion.Value); #endif } else { PhotonNetwork.ConnectUsingSettings(gameVersion.Value); } // reset authentication failure properties. PlayMakerPhotonProxy.lastAuthenticationDebugMessage = string.Empty; PlayMakerPhotonProxy.lastAuthenticationFailed = false; Finish(); }
/// <summary> /// Connect to the Photon Cloud region with the lowest ping (on platforms that support Unity's Ping). /// </summary> /// <remarks> /// Will save the result of pinging all cloud servers in PlayerPrefs. Calling this the first time can take +-2 seconds. /// The ping result can be overridden via PhotonNetwork.OverrideBestCloudServer(..) /// This call can take up to 2 seconds if it is the first time you are using this, all cloud servers will be pinged to check for the best region. /// /// The PUN Setup Wizard stores your appID in a settings file and applies a server address/port. /// To connect to the Photon Cloud, a valid AppId must be in the settings file (shown in the Photon Cloud Dashboard). /// https://dashboard.photonengine.com /// /// Connecting to the Photon Cloud might fail due to: /// - Invalid AppId /// - Network issues /// - Invalid region /// - Subscription CCU limit reached /// - etc. /// /// In general check out the <see cref="DisconnectCause"/> from the <see cref="IConnectionCallbacks.OnDisconnected"/> callback. /// </remarks> /// <returns>If this client is going to connect to cloud server based on ping. Even if true, this does not guarantee a connection but the attempt is being made.</returns> public static async UniTask ConnectToBestCloudServerAsync(CancellationToken token = default) { if (PhotonNetwork.IsConnected) { return; } var task = UniTask.WhenAny( Pun2TaskCallback.OnConnectedToMasterAsync().AsAsyncUnitUniTask(), Pun2TaskCallback.OnDisconnectedAsync()); PhotonNetwork.ConnectToBestCloudServer(); var(winIndex, _, disconnectCause) = await task.WithCancellation(token); if (winIndex == 0) { return; } throw new ConnectionFailedException(disconnectCause); }
public override void OnEnter() { // reset authentication failure properties. PlayMakerPhotonProxy.lastAuthenticationDebugMessage = string.Empty; PlayMakerPhotonProxy.lastAuthenticationFailed = false; bool _result; #if !(UNITY_WINRT || UNITY_WP8 || UNITY_PS3 || UNITY_WIIU) if (!appIdRealtime.IsNone || string.IsNullOrEmpty(appIdRealtime.Value)) { PhotonNetwork.NetworkingClient.AppId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime; } else { PhotonNetwork.NetworkingClient.AppId = appIdRealtime.Value; } if (resetBestRegionInPref.Value) { ServerSettings.ResetBestRegionCodeInPreferences(); } _result = PhotonNetwork.ConnectToBestCloudServer(); #else Debug.Log("Connect to Best Server is not available on this platform"); #endif if (!result.IsNone) { result.Value = _result; } Fsm.Event(_result ? willProceed : willNotProceed); Finish(); }
public void ConnectToBestCloudServer() { PhotonNetwork.NetworkingClient.AppId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime; this.ConnectionPanel.gameObject.SetActive(false); this.AdvancedConnectionPanel.gameObject.SetActive(false); PhotonNetwork.AuthValues = new AuthenticationValues(); PhotonNetwork.AuthValues.UserId = this.UserId; this.ConnectingLabel.SetActive(true); if (this.ResetBestRegionCodeInPreferences) { ServerSettings.ResetBestRegionCodeInPreferences(); } PhotonNetwork.ConnectToBestCloudServer(); if (GameVersionOverride != string.Empty) { PhotonNetwork.GameVersion = GameVersionOverride; } }
/// <summary> /// Starts initializing and connecting to a game. Depends on the selected network mode. /// Sets the current player name prior to connecting to the servers. /// </summary> public static void StartMatch(NetworkMode mode) { PhotonNetwork.automaticallySyncScene = true; PhotonNetwork.playerName = PlayerPrefs.GetString(PrefsKeys.playerName); switch (mode) { //connects to a cloud game available on the Photon servers case NetworkMode.Online: PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.BestRegion; PhotonNetwork.ConnectToBestCloudServer(appVersion); break; //search for open LAN games on the current network, otherwise open a new one case NetworkMode.LAN: PhotonNetwork.ConnectToMaster(PlayerPrefs.GetString(PrefsKeys.serverAddress), 5055, PhotonNetwork.PhotonServerSettings.AppID, appVersion); break; //enable Photon offline mode to not send any network messages at all case NetworkMode.Offline: PhotonNetwork.offlineMode = true; break; } }
void Connect() { PhotonNetwork.ConnectToBestCloudServer("V-A1"); state = 1; }
// Use this for initialization void Start() { //PhotonNetwork.ConnectUsingSettings(versionNumber); PhotonNetwork.ConnectToBestCloudServer(versionNumber); }
public static Task <IResult <DisconnectCause, bool> > ConnectToBestCloudServer(string gameVersion, CancellationToken cancellationToken = default(CancellationToken)) { return(Connect(() => PhotonNetwork.ConnectToBestCloudServer(gameVersion), cancellationToken)); }
void Connect() { PhotonNetwork.ConnectToBestCloudServer("V1.0"); }
/// <summary> /// /// Will Timeout after 60sec /// </summary> /// <returns></returns> public async Task <bool> ConnectToServer() { //if already connected if (!PhotonNetwork.OfflineMode && PhotonNetwork.IsConnectedAndReady) { Debug.Log("Already ConnectedToServer"); return(true); } CurrentPhotonRoomState = PhotonRoomState.Connecting; PhotonNetwork.OfflineMode = false; Debug.Log($"{scriptName} Connecting Server"); if (connectingToMasterServer) { return(await connectMSResult.Task); } SetupConnectSetting(); connectingToMasterServer = true; connectMSResult = new TaskCompletionSource <bool>(); #region Photon way to Connect MasterServer: ConnectToBestCloudServer/ ConnectToRegion/ ConnectToMaster switch (serMasterTarget.smTargetType) { case ServerTarget.ServerMasterTargetType.SpecificMaster: Debug.Log($"{scriptName} ConnectToMaster"); //PhotonNetwork.ConnectToMaster(punMasterTarget.ipAddress, punMasterTarget.serverPort); break; case ServerTarget.ServerMasterTargetType.SpecificRegion: Debug.Log($"{scriptName} ConnectToRegion"); PhotonNetwork.ConnectToRegion(serMasterTarget.photonRegion); break; case ServerTarget.ServerMasterTargetType.BestRegion: default: Debug.Log($"{scriptName} ConnectToCloud"); PhotonNetwork.ConnectToBestCloudServer(); break; } #endregion // Wait until either OnConnectedToMaster() or OnDisconnected await Task.WhenAny(connectMSResult.Task, Task.Delay(60000)); if (!connectMSResult.Task.IsCompleted) { connectMSResult.TrySetResult(false); } if (!PhotonNetwork.IsConnectedAndReady) { await Disconnect(); } connectingToMasterServer = false; return(connectMSResult.Task.Result); }
void Start() { #if USE_PUN StartCoroutine(PumpPlayerInitCoroutine()); var diag = GetComponent <PhotonStatsGui>(); if (diag != null) { diag.enabled = false; } try { // Don't destroy things created by clients. We will need to clean up the // player ghost object only. Even if we're not the master client, we still // need this. Because if the master quits, we might become the master, and // we need to prevent Photon from destroying all objects! if (!PhotonNetwork.inRoom) { PhotonNetwork.autoCleanUpPlayerObjects = false; } else { // Setting this causes an error if we're in a room, but we should make // sure it's false still. Debug.Assert(PhotonNetwork.autoCleanUpPlayerObjects == false); } PhotonNetwork.autoJoinLobby = false; bool isMultiplayer = GameBuilderApplication.CurrentGameOptions.playOptions.isMultiplayer; System.DateTime banLastDate; if (isMultiplayer && IsUserBanned(GetSteamID(), out banLastDate)) { popups.Show($"You have been temporarily banned from multiplayer games for reported inappropriate or abusive behavior. You will be able to play again after {banLastDate.ToString("MMMM dd, yyyy")}.", "Back", () => { scenes.LoadSplashScreen(); }, 800f); return; } if (isMultiplayer) { Util.Log($"Multiplayer!"); SetupPlayerProperties(); mode = Mode.Online; PhotonNetwork.offlineMode = false; } else { } if (PhotonNetwork.connected && PhotonNetwork.inRoom) { // We are still connected and in a room. This is a map switch. mode = Mode.Online; Util.Log($"StayOnline mode. Pretending we just joined the room."); didSwitchMaps = true; OnJoinedRoom(); } else if (PhotonNetwork.connected && PhotonNetwork.insideLobby && isMultiplayer) { // Joining or creating. string roomToJoin = GameBuilderApplication.CurrentGameOptions.joinCode; if (!roomToJoin.IsNullOrEmpty()) { // We're joining a room from the lobby Util.Log($"Trying to join room {roomToJoin}.."); // Try to join existing room PhotonNetwork.JoinRoom(roomToJoin.ToLower()); } else { // We're creating a new game, and happen to be in a lobby already. TryCreateRoom(); } } else { switch (mode) { case Mode.Online: string gameVersion = GetPhotonGameVersion(); // If we're trying to join a game, make sure we connect to their region. string joinCode = GameBuilderApplication.CurrentGameOptions.joinCode; if (joinCode == "*") { // TEMP join random visible game in best region PhotonNetwork.ConnectToBestCloudServer(gameVersion); } else if (joinCode != null) { string regionCodeStr = joinCode.Split(JoinCodeSeparator)[0]; try { CloudRegionCode regionCode = (CloudRegionCode)System.Int32.Parse(regionCodeStr); PhotonNetwork.ConnectToRegion(regionCode, gameVersion); } catch (System.OverflowException) { OnInvalidJoinCodeRegion(); } } else { // Ok we're starting a new game, so just connect to the best. PhotonNetwork.ConnectToBestCloudServer(gameVersion); } break; case Mode.Offline: if (PhotonUtil.ActuallyConnected()) { PhotonNetwork.Disconnect(); } DestroyImmediate(GetComponent <ExitGames.UtilityScripts.PlayerRoomIndexing>()); Util.Log($"Starting offline mode, t = {Time.realtimeSinceStartup}"); PhotonNetwork.offlineMode = true; break; } } } catch (System.FormatException e) { OnFatalError(BadJoinCodeMessage); } catch (System.Exception e) { OnFatalError(e.ToString()); } #else // Non-PUN route mode = Mode.Offline; StartCoroutine(NonPunStartRoutine()); #endif }
// CONECTAR A UM SERVIDOR ------------------------------------------------- //void conectToServer(string server, int port, string id){ // PhotonNetwork.ConnectToMaster ( server, port, id, "1.0"); //} // CONECTAR A NUVEM ------------------------------------------------------- void connectToCloud() { PhotonNetwork.ConnectToBestCloudServer("1.0"); }