public void OnGUI() { if (!PhotonNetworkManager.inRoom) { return; } GUILayout.BeginArea(GuiRect); GUILayout.Label("In-Game"); GUILayout.Label("For simplicity, this demo just shows the players in this room. The list will expand when more join."); GUILayout.Label("Your (random) name: " + PhotonNetworkManager.playerName); GUILayout.Label(PhotonNetworkManager.playerList.Length + " players in this room."); GUILayout.Label("The others are:"); foreach (PhotonPlayer player in PhotonNetworkManager.otherPlayers) { GUILayout.Label(player.ToString()); } if (GUILayout.Button("Leave")) { PhotonNetworkManager.LeaveRoom(); } GUILayout.EndArea(); }
private void Shooting() { Vector2 target = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y)); Vector2 myPos = new Vector2(gunModel.transform.position.x, gunModel.transform.position.y); Vector2 direction = target - myPos; direction.Normalize(); Quaternion rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg); if (characterModel.flipX == false) { //GameObject obj = PhotonNetworkManager.Instantiate(bulletObject.name, new Vector2(aimPos.x, aimPos.y), Quaternion.identity, 0); GameObject projectile = PhotonNetworkManager.Instantiate(bulletObject.name, myPos, rotation, 0); //projectile.GetComponent<Rigidbody2D>().velocity = direction * 5f; } else { //GameObject obj = PhotonNetworkManager.Instantiate(bulletObject.name, new Vector2(aimPos.x, aimPos.y), Quaternion.identity, 0); GameObject projectile = PhotonNetworkManager.Instantiate(bulletObject.name, myPos, rotation, 0); //projectile.GetComponent<Rigidbody2D>().velocity = direction * 5f; //projectile.GetComponent<PhotonView>().RPC("ChangeDirection_Left", PhotonTargets.AllBuffered); } }
protected override void Awake() { base.Awake(); _PhotonNetworkManager = PhotonNetworkManager.Instance; _LobbyManager = LobbyManager.Instance; _PhotonNetworkManager.OnLocalPlayerJoinedRoomEvent.AddListener(OnJoinedRoom); }
public void ConnectToPhoton() { PhotonNetworkManager.ConnectUsingSettings("0.1"); Debug.Log("We have now joined the lobby"); PhotonNetworkManager.LoadLevel("LobbyScene"); }
/// <summary>A thread which runs independent from the Update() calls. Keeps connections online while loading or in background. See PhotonNetwork.BackgroundTimeout.</summary> public static bool FallbackSendAckThread() { if (sendThreadShouldRun && !PhotonNetworkManager.offlineMode && PhotonNetworkManager.networkingPeer != null) { // check if the client should disconnect after some seconds in background if (timerToStopConnectionInBackground != null && PhotonNetworkManager.BackgroundTimeout > 0.1f) { if (timerToStopConnectionInBackground.ElapsedMilliseconds > PhotonNetworkManager.BackgroundTimeout * 1000) { if (PhotonNetworkManager.connected) { PhotonNetworkManager.Disconnect(); } timerToStopConnectionInBackground.Stop(); timerToStopConnectionInBackground.Reset(); return(sendThreadShouldRun); } } if (!PhotonNetworkManager.isMessageQueueRunning || PhotonNetworkManager.networkingPeer.ConnectionTime - PhotonNetworkManager.networkingPeer.LastSendOutgoingTime > 200) { PhotonNetworkManager.networkingPeer.SendAcksOnly(); } } return(sendThreadShouldRun); }
public void OnGUI() { if (this.Skin != null) { GUI.skin = this.Skin; } if (PhotonNetworkManager.isMasterClient) { GUILayout.Label("Controlling client.\nPing: " + PhotonNetworkManager.GetPing()); if (GUILayout.Button("disconnect", GUILayout.ExpandWidth(false))) { PhotonNetworkManager.Disconnect(); } } else if (PhotonNetworkManager.isNonMasterClientInRoom) { GUILayout.Label("Receiving updates.\nPing: " + PhotonNetworkManager.GetPing()); if (GUILayout.Button("disconnect", GUILayout.ExpandWidth(false))) { PhotonNetworkManager.Disconnect(); } } else { GUILayout.Label("Not in room yet\n" + PhotonNetworkManager.connectionStateDetailed); } if (!PhotonNetworkManager.connected && !PhotonNetworkManager.connecting) { if (GUILayout.Button("connect", GUILayout.Width(80))) { PhotonNetworkManager.ConnectUsingSettings(null); // using null as parameter, re-uses previously set version. } } }
// called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues) private static void EditorUpdate() { if (PhotonNetworkManager.PhotonServerSettings == null) { PhotonNetworkManager.CreateSettings(); } if (PhotonNetworkManager.PhotonServerSettings == null) { return; } // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set if (!PhotonNetworkManager.PhotonServerSettings.DisableAutoOpenWizard && PhotonNetworkManager.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet) { ShowRegistrationWizard(); PhotonNetworkManager.PhotonServerSettings.DisableAutoOpenWizard = true; PhotonEditor.SaveSettings(); } // Workaround for TCP crash. Plus this surpresses any other recompile errors. if (EditorApplication.isCompiling) { if (PhotonNetworkManager.connected) { if (lastWarning > EditorApplication.timeSinceStartup - 3) { // Prevent error spam Debug.LogWarning(CurrentLang.WarningPhotonDisconnect); lastWarning = EditorApplication.timeSinceStartup; } PhotonNetworkManager.Disconnect(); } } }
/// <summary> /// Start the connection process. /// - If already connected, we attempt joining a random room /// - if not yet connected, Connect this application instance to Photon Cloud Network /// </summary> public void Connect() { // we want to make sure the log is clear everytime we connect, we might have several failed attempted if connection failed. feedbackText.text = ""; // keep track of the will to join a room, because when we come back from the game we will get a callback that we are connected, so we need to know what to do then isConnecting = true; // hide the Play button for visual consistency controlPanel.SetActive(false); // start the loader animation for visual effect. if (loaderAnime != null) { loaderAnime.StartLoaderAnimation(); } // we check if we are connected or not, we join if we are , else we initiate the connection to the server. if (PhotonNetworkManager.connected) { LogFeedback("Joining Room..."); // #Critical we need at this point to attempt joining a Random Room. If it fails, we'll get notified in OnPhotonRandomJoinFailed() and we'll create one. PhotonNetworkManager.JoinRandomRoom(); } else { LogFeedback("Connecting..."); // #Critical, we must first and foremost connect to Photon Online Server. PhotonNetworkManager.ConnectUsingSettings(_gameVersion); } }
public override void OnConnectedToMaster() { // after connect this.UserId = PhotonNetworkManager.player.UserId; ////Debug.Log("UserID " + this.UserId); if (PlayerPrefs.HasKey(previousRoomPlayerPrefKey)) { Debug.Log("getting previous room from prefs: "); this.previousRoom = PlayerPrefs.GetString(previousRoomPlayerPrefKey); PlayerPrefs.DeleteKey(previousRoomPlayerPrefKey); // we don't keep this, it was only for initial recovery } // after timeout: re-join "old" room (if one is known) if (!string.IsNullOrEmpty(this.previousRoom)) { Debug.Log("ReJoining previous room: " + this.previousRoom); PhotonNetworkManager.ReJoinRoom(this.previousRoom); this.previousRoom = null; // we only will try to re-join once. if this fails, we will get into a random/new room } else { // else: join a random room PhotonNetworkManager.JoinRandomRoom(); } }
/// <summary> /// Calculates an estimated position based on the last synchronized position, /// the time when the last position was received and the movement speed of the object /// </summary> /// <returns>Estimated position of the remote object</returns> public Vector3 GetExtrapolatedPositionOffset() { float timePassed = (float)(PhotonNetworkManager.time - m_LastSerializeTime); if (m_Model.ExtrapolateIncludingRoundTripTime == true) { timePassed += (float)PhotonNetworkManager.GetPing() / 1000f; } Vector3 extrapolatePosition = Vector3.zero; switch (m_Model.ExtrapolateOption) { case PhotonTransformViewPositionModel.ExtrapolateOptions.SynchronizeValues: Quaternion turnRotation = Quaternion.Euler(0, m_SynchronizedTurnSpeed * timePassed, 0); extrapolatePosition = turnRotation * (m_SynchronizedSpeed * timePassed); break; case PhotonTransformViewPositionModel.ExtrapolateOptions.FixedSpeed: Vector3 moveDirection = (m_NetworkPosition - GetOldestStoredNetworkPosition()).normalized; extrapolatePosition = moveDirection * m_Model.ExtrapolateSpeed * timePassed; break; case PhotonTransformViewPositionModel.ExtrapolateOptions.EstimateSpeedAndTurn: Vector3 moveDelta = (m_NetworkPosition - GetOldestStoredNetworkPosition()) * PhotonNetworkManager.sendRateOnSerialize; extrapolatePosition = moveDelta * timePassed; break; } return(extrapolatePosition); }
public void LogStats() { if (this.LogTrafficStats) { Debug.Log("SupportLogger " + PhotonNetworkManager.NetworkStatisticsToString()); } }
public void ChangeBoolValue() { if (SceneManager.GetActiveScene().name == "Menu principal" || SceneManager.GetActiveScene().name == "Menu without logic") { GameObject.Find("CanvasFirstPlayer/Background").GetComponent <MenuActions>().ChangeLevel(); } else { PhotonNetworkManager photonNetworkManager = GameObject.Find("GameLogic").GetComponent <PhotonNetworkManager>(); if (PhotonNetwork.isMasterClient) { if (photonNetworkManager.IsOver) { photonNetworkManager.IsPlayingLocal = false; photonNetworkManager.IsOver = false; PhotonNetwork.LoadLevel("Menu without logic"); } else { PhotonNetwork.LoadLevel(6 + photonNetworkManager.GetMusiqueLevel); } } } }
public override void OnJoinedRoom() { GameObject monster = PhotonNetworkManager.Instantiate("monsterprefab", Vector3.zero, Quaternion.identity, 0); monster.GetComponent <myThirdPersonController>().isControllable = true; myPhotonView = monster.GetComponent <PhotonView>(); }
/// <summary> /// Finds scenes in "Assets/Photon Unity Networking/Demos/", excludes those in folder "PUNGuide_M2H" and applies remaining scenes to build settings. The one with "Hub" in it first. /// </summary> public static void SetPunDemoBuildSettings() { string _PunPath = string.Empty; string _thisPath = PhotonNetworkManager.FindAssetPath("PunStartUp"); _thisPath = Application.dataPath + _thisPath.Substring(6); // remove "Assets/" _PunPath = PhotonEditorUtils.GetParent(_thisPath, "Photon Unity Networking"); if (_PunPath == null) { _PunPath = Application.dataPath + "Photon Unity Networking"; } // find path of pun guide string[] tempPaths = Directory.GetDirectories(_PunPath, "Demos", SearchOption.AllDirectories); if (tempPaths == null || tempPaths.Length != 1) { return; } // find scenes of guide string guidePath = tempPaths[0]; tempPaths = Directory.GetFiles(guidePath, "*.unity", SearchOption.AllDirectories); if (tempPaths == null || tempPaths.Length == 0) { return; } // add found guide scenes to build settings List <EditorBuildSettingsScene> sceneAr = new List <EditorBuildSettingsScene>(); for (int i = 0; i < tempPaths.Length; i++) { //Debug.Log(tempPaths[i]); string path = tempPaths[i].Substring(Application.dataPath.Length - "Assets".Length); path = path.Replace('\\', '/'); //Debug.Log(path); if (path.Contains("PUNGuide_M2H")) { continue; } // edited to avoid old scene to be included. if (path.Contains("DemoHub-Scene-V2")) { sceneAr.Insert(0, new EditorBuildSettingsScene(path, true)); continue; } sceneAr.Add(new EditorBuildSettingsScene(path, true)); } EditorBuildSettings.scenes = sceneAr.ToArray(); EditorSceneManager.OpenScene(sceneAr[0].path); }
private void SpawnPlayer() { GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag("SpawnPoint"); int randomSpawnPoint = Random.Range(0, spawnPoints.Length); PhotonNetworkManager.Instantiate(mainPlayer.name, spawnPoints[randomSpawnPoint].transform.position, mainPlayer.transform.rotation, 0); }
//[MenuItem("Window/Photon Unity Networking/PUN Demo Loader Reset")] //protected static void ResetDemoLoader() //{ // EditorPrefs.DeleteKey("PunDemosOpenedBefore"); //} public static void LoadPunDemoHub() { string _hubScene = PhotonNetworkManager.FindAssetPath("DemoHub-Scene-V2 t:scene"); EditorSceneManager.OpenScene(_hubScene); Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(_hubScene); }
public void OnClickJoinRoom() { RoomOptions roomOptions = new RoomOptions(); roomOptions.MaxPlayers = 4; PhotonNetworkManager.JoinOrCreateRoom(joinRoomInput.text, roomOptions, TypedLobby.Default); }
void Start() { _view = GetComponent <PhotonView>(); //Obtengo el View _anim = GetComponent <Animator>(); //Obtengo el Animator asourc = GetComponent <AudioSource>(); rb = GetComponent <Rigidbody>(); _life = 3; //Seteo mi vida kills = 0; win = GameObject.Find("Canvas").transform.GetChild(3).gameObject; if (!isFromThisClient) { return; } else { networkManager = FindObjectOfType <PhotonNetworkManager>(); lifeText = GameObject.Find("PlayerCanvas").transform.GetChild(2).GetComponent <Text>(); defeat = GameObject.Find("Canvas").transform.GetChild(4).gameObject; win = GameObject.Find("Canvas").transform.GetChild(3).gameObject; Cursor.lockState = CursorLockMode.Locked; CameraSetUp(); FindObjectsOfType <Controller>().Where(x => x.GetComponent <PhotonView>().IsMine).FirstOrDefault().myHero = this; player_name = FindObjectOfType <PhotonNetworkManager>().playerName; head.gameObject.SetActive(false); PlayerSyncName(player_name); ServerNetwork.Instance.RequestSetName(); } }
public IEnumerator DestroyRpc() { GameObject.Destroy(this.gameObject); yield return(0); // if you allow 1 frame to pass, the object's OnDestroy() method gets called and cleans up references. PhotonNetworkManager.UnAllocateViewID(this.photonView.viewID); }
private void Start() { _idToPlayer = new Dictionary <string, Player>(); List <Player.PlayerModel> playerModels = PhotonNetworkManager.GetPlayerModels(); if (playerModels != null) { for (int i = 0; i < playerModels.Count; i++) { Player.PlayerModel playerModel = playerModels[i]; playerModel.heroSpawnCoord = _model.playerHeroSpawnPositions[i]; Player player = Player.CreatePlayer(this, playerModel, transform); _idToPlayer.Add(playerModel.id, player); } } else { // playerModels will be null when starting the game from the game scene rather than the start scene for (int i = 0; i < _devPlayers.Count; i++) { Player.PlayerModel playerModel = _devPlayers[i]; playerModel.heroSpawnCoord = _model.playerHeroSpawnPositions[i]; Player player = Player.CreatePlayer(this, playerModel, transform); _idToPlayer.Add(playerModel.id, player); } } _model.actions = new List <Tuple <PlayerAction.EType, PlayerAction> >(); _board = GetComponentInChildren <Board>(); PhotonNetwork.NetworkingClient.EventReceived += OnEvent; }
public void OnGUI() { if (GUILayout.Button("Return to Lobby")) { PhotonNetworkManager.LeaveRoom(); // we will load the menu level when we successfully left the room } }
/// <summary> /// MonoBehaviour method called on GameObject by Unity during initialization phase. /// </summary> void Start() { Instance = this; // in case we started this demo with the wrong scene being active, simply load the menu scene if (!PhotonNetworkManager.connected) { SceneManager.LoadScene("PunBasics-Launcher"); return; } if (playerPrefab == null) // #Tip Never assume public properties of Components are filled up properly, always check and inform the developer of it. { Debug.LogError("<Color=Red><b>Missing</b></Color> playerPrefab Reference. Please set it up in GameObject 'Game Manager'", this); } else { if (PlayerManager.LocalPlayerInstance == null) { Debug.Log("We are Instantiating LocalPlayer from " + SceneManagerHelper.ActiveSceneName); // we're in a room. spawn a character for the local player. it gets synced by using PhotonNetwork.Instantiate PhotonNetworkManager.Instantiate(this.playerPrefab.name, new Vector3(0f, 5f, 0f), Quaternion.identity, 0); } else { Debug.Log("Ignoring scene load for " + SceneManagerHelper.ActiveSceneName); } } }
/// <summary> /// Call to send an action. Optionally finish the turn, too. /// The move object can be anything. Try to optimize though and only send the strict minimum set of information to define the turn move. /// </summary> /// <param name="move"></param> /// <param name="finished"></param> public void SendMove(object move, bool finished) { if (IsFinishedByMe) { UnityEngine.Debug.LogWarning("Can't SendMove. Turn is finished by this player."); return; } // along with the actual move, we have to send which turn this move belongs to Hashtable moveHt = new Hashtable(); moveHt.Add("turn", Turn); moveHt.Add("move", move); byte evCode = (finished) ? EvFinalMove : EvMove; PhotonNetworkManager.RaiseEvent(evCode, moveHt, true, new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache }); if (finished) { PhotonNetworkManager.player.SetFinishedTurn(Turn); } // the server won't send the event back to the origin (by default). to get the event, call it locally // (note: the order of events might be mixed up as we do this locally) OnEvent(evCode, moveHt, PhotonNetworkManager.player.ID); }
private void OnGUI() { if (this.HideUI) { return; } GUILayout.BeginArea(new Rect(0, 0, 300, Screen.height)); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); if (!PhotonNetworkManager.connected) { if (GUILayout.Button("Connect", GUILayout.Width(100))) { PhotonNetworkManager.ConnectUsingSettings(null); } } else { if (GUILayout.Button("Disconnect", GUILayout.Width(100))) { PhotonNetworkManager.Disconnect(); } } GUILayout.Label(PhotonNetworkManager.connectionStateDetailed.ToString()); GUILayout.EndHorizontal(); GUILayout.EndArea(); }
public virtual void OnPhotonRandomJoinFailed() { Debug.Log("OnPhotonRandomJoinFailed() was called by PUN. No random room available, so we create one. Calling: PhotonNetwork.CreateRoom(null, new RoomOptions() {maxPlayers = 4}, null);"); PhotonNetworkManager.CreateRoom(null, new RoomOptions() { MaxPlayers = 4 }, null); }
void CreatePlayerObject() { Vector3 position = new Vector3(33.5f, 1.5f, 20.5f); GameObject newPlayerObject = PhotonNetworkManager.Instantiate("Robot Kyle RPG", position, Quaternion.identity, 0); Camera.Target = newPlayerObject.transform; }
protected override void SingletonStart() { _PhotonNetworkManager = PhotonNetworkManager.Instance; // Subscribing to events _PhotonNetworkManager.OnLocalPlayerJoinedRoomEvent.AddListener(OnLocalPlayerEnteredRoom); _PhotonNetworkManager.OnLocalPlayerLeftRoomEvent.AddListener(OnLocalPlayerLeftRoom); }
public override void OnPhotonRandomJoinFailed(object[] codeAndMsg) { Debug.Log("OnPhotonRandomJoinFailed"); PhotonNetworkManager.CreateRoom(null, new RoomOptions() { MaxPlayers = 2, PlayerTtl = 20000 }, null); }
void Start() { if (PhotonNetworkManager.connected || PhotonNetworkManager.connecting) { PhotonNetworkManager.Disconnect(); } m_Headline = new GUIStyle(this.Skin.label); m_Headline.padding = new RectOffset(3, 0, 0, 0); }
public void checkServerList() { serverList.text = ""; RoomInfo[] rooms = PhotonNetworkManager.GetRoomList(); for (var i = 0; i < rooms.Length; i++) { serverList.text = serverList.text + rooms[i].ToString(); } }