protected virtual void ReceivePlayerState(ExitGames.Client.Photon.Hashtable gameState, PhotonMessageInfo info) { //Debug.Log("GOT PLAYER STATE!"); if ((info.sender != PhotonNetwork.masterClient) || (info.sender.isLocal)) { return; } // -------- refresh stats of all included players -------- foreach (vp_MPNetworkPlayer player in vp_MPNetworkPlayer.Players.Values) { if (player == null) { continue; } object stats; if (gameState.TryGetValue(player.ID, out stats) && (stats != null)) { player.Stats.SetFromHashtable((ExitGames.Client.Photon.Hashtable)stats); } //else // vp_MPDebug.Log("Failed to extract player " + player.ID + " stats from gamestate"); } // -------- refresh all teams -------- if (vp_MPTeamManager.Exists) { vp_MPTeamManager.Instance.RefreshTeams(); } }
public void OnJoinRoomButton(string gameMode) { ExitGames.Client.Photon.Hashtable expectecProperties = new ExitGames.Client.Photon.Hashtable(); expectecProperties.Add(gameMode, 1); PhotonNetwork.JoinRandomRoom(expectecProperties, 0); }
public void GetAllPlayerUnitData() { if (IsMultiPlayer) { ExitGames.Client.Photon.Hashtable hs = new ExitGames.Client.Photon.Hashtable(); hs = PhotonNetwork.room.CustomProperties; if (hs.ContainsKey("Players")) { PF_GamePlay.AllSavedCharacterUnitData = new Dictionary <string, FG_SavedCharacter>(); string[] playerNames = (string[])hs["Players"]; for (int i = 0; i < playerNames.Length; i++) { PhotonPlayer player = PhotonNetwork.playerList.ToList().Find(x => x.UserId.Contains(playerNames[i])); FG_SavedCharacter saved = PlayFab.Json.PlayFabSimpleJson.DeserializeObject <FG_SavedCharacter>((string)player.CustomProperties["SavedData"]); PF_GamePlay.AllSavedCharacterUnitData.Add(playerNames[i], saved); } } else { Debug.Log("room prperties do not contain the key player"); } } else { } }
/// <summary> /// pushes the master client's version of the game state and all /// player stats onto another client. if 'player' is null, the game /// state will be pushed onto _all_ other clients. 'gameState' can /// optionally be provided for cases where only a partial game state /// (a few stats on a few players) needs to be sent. by default the /// method will assemble and broadcast all stats of all players. /// </summary> public void TransmitGameState(PhotonPlayer targetPlayer, ExitGames.Client.Photon.Hashtable gameState = null) { if (!PhotonNetwork.isMasterClient) { return; } //DumpGameState(gameState); // if no (partial) gamestate has been provided, assemble and // broadcast the entire gamestate if (gameState == null) { gameState = AssembleGameState(); } //DumpGameState(gameState); if (targetPlayer == null) { //Debug.Log("sending to all" + Time.time); photonView.RPC("ReceiveGameState", PhotonTargets.Others, (ExitGames.Client.Photon.Hashtable)gameState); } else { //Debug.Log("sending to " + targetPlayer + "" + Time.time); photonView.RPC("ReceiveGameState", targetPlayer, (ExitGames.Client.Photon.Hashtable)gameState); } if (vp_MPTeamManager.Exists) { vp_MPTeamManager.Instance.RefreshTeams(); } }
/// <summary> /// /// </summary> public void QuickPlay() { if (!PhotonNetwork.connected || Joining) { return; } string rn = string.Format("Room {0}", Random.Range(0, 9999)); //Create hastable to send room information from lobby. ExitGames.Client.Photon.Hashtable roomOption = new ExitGames.Client.Photon.Hashtable(); //Add information in hashtable. roomOption[PropiertiesKeys.TimeRoomKey] = RoomTime[r_Time]; roomOption[PropiertiesKeys.RoomRoundKey] = "0"; roomOption[PropiertiesKeys.SceneNameKey] = SceneManager[CurrentScene].SceneName; roomOption[PropiertiesKeys.RoomState] = "False"; string[] properties = new string[4]; properties[0] = PropiertiesKeys.RoomRoundKey; properties[1] = PropiertiesKeys.TimeRoomKey; properties[2] = PropiertiesKeys.SceneNameKey; properties[3] = PropiertiesKeys.RoomState; PhotonNetwork.JoinOrCreateRoom(rn, new RoomOptions() { MaxPlayers = 8, CleanupCacheOnLeave = true, CustomRoomProperties = roomOption, CustomRoomPropertiesForLobby = properties }, null); Joining = true; UI.ShowLookingUI(true); }
/// <summary> /// creates a hashtable with only a few of the stats of a /// certain player /// </summary> protected virtual ExitGames.Client.Photon.Hashtable ExtractPlayerStats(vp_MPNetworkPlayer player, params string[] stats) { if (!PhotonNetwork.isMasterClient) { return(null); } // create a player hashtable with only the given stats ExitGames.Client.Photon.Hashtable table = new ExitGames.Client.Photon.Hashtable(); //string str = "Extracting stats for player: " + vp_MPNetworkPlayer.GetName(player.ID); foreach (string s in stats) { object o = player.Stats.Get(s); if (o == null) { Debug.LogError("Error: (" + this + ") Player stat '" + s + "' could not be retrieved from player " + player.ID + "."); continue; } table.Add(s, o); //str += ": " + s + "(" + o + ")"; } //Debug.Log(str); return(table); }
public void GetLevelData() { if (IsMultiPlayer) { ExitGames.Client.Photon.Hashtable hs = new ExitGames.Client.Photon.Hashtable(); hs = PhotonNetwork.room.CustomProperties; if (hs.ContainsKey("Level")) { PF_GamePlay.ActiveQuest = new FG_LevelData(); PF_GamePlay.ActiveQuest = PF_GameData.Levels[(string)hs["Level"]]; } else { Debug.LogError(" level is not include "); } } else { //if (PF_GamePlay.ActiveQuest != null) //else //{ // Debug.LogError(" PF_gameplay do not get the data "); //} } }
public bool OtherRoomsFound(string oldType) { List <RoomInfo> tempListOfRooms = new List <RoomInfo>(); RoomInfo selectedRoom = null; Debug.Log("available rooms: " + roomsListings.Count); string newType; if (oldType == "single") { newType = "match"; } else { newType = "single"; } foreach (RoomInfo room in roomsListings) { Hashtable expectedCustomRoomProperties = new Hashtable() { { "type", newType } }; Debug.Log(room.Name + " is a " + room.CustomProperties["type"]); } foreach (RoomInfo room in roomsListings) { ExitGames.Client.Photon.Hashtable roomProperties = new ExitGames.Client.Photon.Hashtable(); roomProperties = room.CustomProperties; string roomType = (string)room.CustomProperties["type"]; Debug.Log(room.Name + " is a " + roomType); string roomProps = (string)roomProperties["type"]; Debug.Log(room.Name + " is a " + roomProps); if (room.CustomProperties.ContainsValue(newType) && room.IsOpen && room.IsVisible) { tempListOfRooms.Add(room); selectedRoom = room; Debug.Log("found this room: " + selectedRoom.Name); } } if (tempListOfRooms.Count > 0) { Debug.Log("List of found rooms contains: " + tempListOfRooms.Count); } else { Debug.Log("didnt find any room of " + newType + " type, now create one"); } return(false); }
public void SearchForRoomOfType(string type) { List <RoomInfo> tempListOfRooms = new List <RoomInfo>(); RoomInfo selectedRoom = null; Debug.Log("available rooms: " + roomsListings.Count); StartCoroutine(WaitingTimer(type)); foreach (RoomInfo room in roomsListings) { Hashtable expectedCustomRoomProperties = new Hashtable() { { "type", type } }; Debug.Log(room.Name + " is a " + room.CustomProperties["type"]); } foreach (RoomInfo room in roomsListings) { ExitGames.Client.Photon.Hashtable roomProperties = new ExitGames.Client.Photon.Hashtable(); roomProperties = room.CustomProperties; string roomType = (string)room.CustomProperties["type"]; Debug.Log(room.Name + " is a " + roomType); string roomProps = (string)roomProperties["type"]; Debug.Log(room.Name + " is a " + roomProps); if (room.CustomProperties.ContainsValue(type) && room.IsOpen && room.IsVisible) { tempListOfRooms.Add(room); selectedRoom = room; Debug.Log("found this room: " + selectedRoom.Name); } } if (tempListOfRooms.Count > 0) { Debug.Log("List of found rooms contains: " + tempListOfRooms.Count); } else { Debug.Log("didnt find any room of " + type + " type, now create one"); } if (selectedRoom != null) { PhotonNetwork.JoinRoom(selectedRoom.Name); } else { //Promp to join a diferent type CreateRoomOnJoinFaield(type); } }
private IEnumerator SetPlayerPing() { ExitGames.Client.Photon.Hashtable table = new ExitGames.Client.Photon.Hashtable(); table["ping"] = PhotonNetwork.GetPing(); PhotonNetwork.player.SetCustomProperties(table); yield return(new WaitForSeconds(5)); StartCoroutine(SetPlayerPing()); }
/// <summary> /// Clear all properties from this Room. /// </summary> /// <param name="player"></param> public static void ClearAllProperties(this Room room) { ExitGames.Client.Photon.Hashtable t = room.CustomProperties; List<object> keys = new List<object>(t.Keys); for (int i = 0, imax = keys.Count; i < imax; i++) { t[keys[i]] = null; } room.SetCustomProperties(t); }
private void SetPlayerTeam(Player player) { var propsToSet = new ExitGames.Client.Photon.Hashtable() { { "Team", nextTeam }, { "KEY", "Value" } }; player.SetCustomProperties(propsToSet); nextTeam = (nextTeam == 1) ? (byte)2 : (byte)1; }
void EnterPlayerRoom() { ExitGames.Client.Photon.Hashtable PlayerProps = new ExitGames.Client.Photon.Hashtable(); PlayerProps.Add("Alive", true); PlayerProps.Add("RoomState", RoomPlayerState.Enter); PlayerProps.Add("CharacterName", ""); PlayerProps.Add("Ready", false); PhotonNetwork.SetPlayerCustomProperties(PlayerProps); //PhotonNetwork.JoinLobby(); PhotonNetwork.LoadLevel("GameRoomView"); }
public override void OnPlayerPropertiesUpdate(Player targetPlayer, ExitGames.Client.Photon.Hashtable changedProps) { if (changedProps.ContainsKey("RoomState") && CheckAllReady()) { Debug.Log("All Ready"); PhotonNetwork.LoadLevel("GameGround"); } else { Debug.Log("Not Yet"); } }
public override void OnCreatedRoom() { Debug.Log("check1"); ExitGames.Client.Photon.Hashtable roomProperties = new ExitGames.Client.Photon.Hashtable(); //roomProperties["type"] = "single"; roomProperties.Add("type", "single"); //room.SetCustomProperties() roomController.roomProperty = roomProperties; string roomType = (string)roomController.roomProperty["type"]; Debug.Log(roomType); }
public override void OnPlayerPropertiesUpdate(Player targetPlayer, ExitGames.Client.Photon.Hashtable changedProps) { if (!GameControllerGamePlay.Instance.GetIsOffline()) { //verifica se este objeto é o mesmo jogador (targetPlayer) que está no parâmetro deste método if (photonView.Owner.ActorNumber != targetPlayer.ActorNumber) { return; } object tempValue; changedProps.TryGetValue("score", out tempValue); playerScoreText.text = "Score: " + tempValue.ToString(); } }
private void SetCustomProperties(PhotonPlayer player, int gender, int hairIndex, int hairColor, int eyesIndex, int eyesColor, int position, int chest, int hands, int WeaponMain, int Legs, int Boots, int WeaponOff) { ExitGames.Client.Photon.Hashtable customProperties = new ExitGames.Client.Photon.Hashtable() { { "gender", gender }, { "hairIndex", hairIndex }, { "hairColor", hairColor }, { "eyesIndex", eyesIndex }, { "eyesColor", eyesColor }, { "spawn", position }, { "chest", chest }, { "hands", hands }, { "WeaponMain", WeaponMain }, { "Legs", Legs }, { "Boots", Boots }, { "WeaponOff", WeaponOff }, }; player.SetCustomProperties(customProperties); }
public void CreateandJoinRoom() { if (UIManager.uiManagerInstance.pvpModestate == PVPType.PublicGame) { string randomRoomName = GenerateRandomRoomName() + Random.Range(10000, 100000).ToString(); Debug.Log("Room name..." + randomRoomName); //Room_Name = float.Parse(randomRoomName); RoomOptions roomOptions = new RoomOptions(); roomOptions.IsOpen = true; roomOptions.IsVisible = true; roomOptions.MaxPlayers = 2; ExitGames.Client.Photon.Hashtable RoomCustomProps = new ExitGames.Client.Photon.Hashtable(); roomOptions.CustomRoomProperties = RoomCustomProps; PhotonNetwork.CreateRoom(randomRoomName, roomOptions); } }
/// <summary> /// broadcasts a game state consisting of an individual array /// of stats extracted from each specified player. parameters /// 2 and up should be arrays of strings identifying the stats /// included for each respective player. the returned gamestate /// may include unique stat names for each player /// </summary> public void TransmitPlayerState(int[] playerIDs, params string[][] stats) { if (!PhotonNetwork.isMasterClient) { return; } ExitGames.Client.Photon.Hashtable state = AssembleGameStatePartial(playerIDs, stats); if (state == null) { Debug.LogError("Error: (" + this + ") Failed to assemble partial gamestate."); return; } photonView.RPC("ReceivePlayerState", PhotonTargets.Others, (ExitGames.Client.Photon.Hashtable)state); }
/// <summary> /// assembles a game state consisting of an individual array /// of stats extracted from each specified player. parameters /// 2 and up should be arrays of strings identifying the stats /// included for each respective player. the returned gamestate /// may include unique stat names for every player /// </summary> protected virtual ExitGames.Client.Photon.Hashtable AssembleGameStatePartial(int[] playerIDs, params string[][] stats) { ExitGames.Client.Photon.Hashtable state = new ExitGames.Client.Photon.Hashtable(); for (int v = 0; v < playerIDs.Length; v++) { if (state.ContainsKey(playerIDs[v])) // safety measure in case int array has duplicate id:s { Debug.LogWarning("Warning (" + this + ") Trying to add same player twice to a partial game state (not good). Duplicates will be ignored."); continue; } state.Add(playerIDs[v], ExtractPlayerStats(vp_MPNetworkPlayer.Get(playerIDs[v]), stats[v])); } return(state); }
//Set finished attribute for all players to false //position all players at the start //load new level public void LoadNextLevel() { foreach (Player p in PhotonNetwork.PlayerList) { ExitGames.Client.Photon.Hashtable props = new ExitGames.Client.Photon.Hashtable() { { "finished", false } }; p.SetCustomProperties(props); } //uses a random player's photonview? Idk might not be the best idea GameObject.FindObjectOfType <PhotonView>().RPC("MoveToStartPosition", RpcTarget.All); currentLevelIndex++; PhotonNetwork.LoadLevel(levels[currentLevelIndex]); //wow this is a big ol line of code //PhotonNetwork.LoadLevel(SceneManager.GetSceneByBuildIndex(SceneManager.GetActiveScene().buildIndex + 1).name); }
/// <summary> /// Called by UI buttons; will queue the player based on the given map name /// </summary> /// <param name="mapName">The name of the map to put the player in</param> public void Play(string mapName) { gameHandler.currentMap = mapManager.GetMap(mapName); // Check to see if we are on the network and not already in a room if (PhotonNetwork.connected && PhotonNetwork.room == null) { // Find a room to join lobbyState = LobbyStates.searching; // Set room properties so that we can be found by other players looking for the same game (equivalent to matchmaking) Hashtable expectedCustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "m", gameHandler.currentMap.name } }; PhotonNetwork.JoinRandomRoom(expectedCustomRoomProperties, 0); } }
// Start is called before the first frame update void Start() { foreach (var player in PhotonNetwork.CurrentRoom.Players) { if (!player.Value.IsLocal) { var properties = new ExitGames.Client.Photon.Hashtable() { { "StoryText", "..." }, { "Choice0", "" }, { "Choice1", "" }, { "Choice2", "" }, { "Continue", false }, { "Pick", -1 }, { "ActorId", 1 } }; player.Value.SetCustomProperties(properties); } } }
/// <summary> /// Create a new room photon /// </summary> /// <param name="mInput"></param> /// <param name="MaxPlayers"></param> public void CreateRoom(InputField mInput) { //Avoid to request double connection. if (Joining) { Debug.Log("Already Request a connection, wait for server response."); return; } if (!String.IsNullOrEmpty(mInput.text)) { //Create hastable to send room information from lobby. ExitGames.Client.Photon.Hashtable roomOption = new ExitGames.Client.Photon.Hashtable(); //Add information in hashtable. roomOption[PropiertiesKeys.TimeRoomKey] = RoomTime[r_Time]; roomOption[PropiertiesKeys.RoomRoundKey] = GamePerRounds ? "1" : "0"; roomOption[PropiertiesKeys.SceneNameKey] = SceneManager[CurrentScene].SceneName; roomOption[PropiertiesKeys.RoomState] = "False"; string[] properties = new string[4]; properties[0] = PropiertiesKeys.RoomRoundKey; properties[1] = PropiertiesKeys.TimeRoomKey; properties[2] = PropiertiesKeys.SceneNameKey; properties[3] = PropiertiesKeys.RoomState; int mp = MaxPlayers[m_MaxPlayer]; PhotonNetwork.CreateRoom(mInput.text, new RoomOptions() { MaxPlayers = (byte)mp, CleanupCacheOnLeave = true, CustomRoomProperties = roomOption, CustomRoomPropertiesForLobby = properties }, null); Joining = true; } else { Debug.Log("Room Name can not be empty!"); } }
public override void OnPlayerPropertiesUpdate(Player targetPlayer, ExitGames.Client.Photon.Hashtable changedProps) { EntryUpdate(targetPlayer, false); if (CheackAllReady()) { // Battle Debug.Log("All Ready"); if (GameBalance) { if (IsBalance) { Hashtable props = new Hashtable { { "Running Game", true } }; PhotonNetwork.CurrentRoom.SetCustomProperties(props); PhotonNetwork.LoadLevel("GameGround"); } else { Debug.Log("Is Not a Balance Game, Can't Start"); } } else { Hashtable props = new Hashtable { { "Running Game", true } }; PhotonNetwork.CurrentRoom.SetCustomProperties(props); PhotonNetwork.LoadLevel("GameGround"); } } else { Debug.Log("Not All Ready yet"); } }
public override void OnPlayerPropertiesUpdate(Realtime.Player target, ExitGames.Client.Photon.Hashtable changedProps) { //Debug.Log("OnPlayerPropertiesUpdate " + target.ActorNumber + " " + target.ToStringFull() + " " + changedProps.ToStringFull()); //Debug.Log("_player.ID " + _player.ActorNumber); if (_player.ActorNumber == target.ActorNumber) { foreach (DictionaryEntry entry in changedProps) { string _key = this.ParseKey(entry.Key); if (this.builtInPropsCellList.ContainsKey(_key)) { this.builtInPropsCellList[_key].UpdateInfo(entry.Value.ToString()); } else { this.AddProperty(_key, entry.Value.ToString(), this.CustomPropertiesPanel); } } } StartCoroutine("UpdateUIPing"); }
private void sendGameInitEvent() { int randomSeed = Environment.TickCount; CardDeck customerDeck = CardDeck.FromFile("Decks/CustomerDeck"); customerDeck.Shuffle(randomSeed); CardDeck ingredientDeck = CardDeck.FromFile("Decks/IngredientDeck"); ingredientDeck.Shuffle(randomSeed); Hashtable contents = new ExitGames.Client.Photon.Hashtable(); contents.Add("customerDeck", CardDeck.ToJson(customerDeck, false)); contents.Add("ingredientDeck", CardDeck.ToJson(ingredientDeck, false)); contents.Add("playerList", getSerializablePlayerList(_roomController.GetPlayerList())); RaiseEventOptions options = new RaiseEventOptions(); options.Receivers = ReceiverGroup.All; PhotonNetwork.RaiseEvent(NetworkOpCodes.INITIAL_GAME_STATE, contents, true, options); }
/// <summary> /// dumps a game state hashtable to the console /// </summary> public static void DumpGameState(ExitGames.Client.Photon.Hashtable gameState) { string s = "--- GAME STATE ---\n(click to view)\n\n"; if (gameState == null) { Debug.Log("DumpGameState: Passed gamestate was null: assembling full gamestate."); gameState = AssembleGameState(); } foreach (object key in gameState.Keys) { if (key.GetType() == typeof(int)) { object player; gameState.TryGetValue(key, out player); s += vp_MPNetworkPlayer.GetName((int)key) + ":\n"; foreach (object o in ((ExitGames.Client.Photon.Hashtable)player).Keys) { s += "\t\t" + (o.ToString()) + ": "; object val; ((ExitGames.Client.Photon.Hashtable)player).TryGetValue(o, out val); s += val.ToString().Replace("(System.String)", "") + "\n"; } } else { object val; gameState.TryGetValue(key, out val); s += key.ToString() + ": " + val.ToString(); } s += "\n"; } UnityEngine.Debug.Log(s); }
public override void OnJoinedRoom() { if (IsMaster) { PhoneInit.PlayerId = 5; } GameObject.FindObjectOfType <Text>().text = "Room " + PhotonNetwork.CurrentRoom.Name + " joined."; Debug.Log("Status " + PhotonNetwork.IsConnected + " Room: " + PhotonNetwork.CurrentRoom.Name); ExitGames.Client.Photon.Hashtable properties = new ExitGames.Client.Photon.Hashtable() { { "StoryText", "" }, { "Choice0", "" }, { "Choice1", "" }, { "Choice2", "" }, { "Continue", false }, { "Pick", -1 }, { "ActorId", PhoneInit.PlayerId }, { "ActorProuns", PhoneInit.PlayerGender } }; PhotonNetwork.LocalPlayer.SetCustomProperties(properties); if (PhotonNetwork.CurrentRoom != null && PhotonNetwork.CurrentRoom.PlayerCount > 2 && IsMaster) { if (IsSplit) { SceneManager.LoadScene("Birthday2"); } else { SceneManager.LoadScene("Birthday1"); } } else if (PhotonNetwork.CurrentRoom != null && PhotonNetwork.CurrentRoom.PlayerCount > 2 && !IsMaster) { SceneManager.LoadScene("PhoneScreen"); } }
public void OnPhotonPlayerPropertiesChanged(object[] playerAndUpdatedProps) { PhotonPlayer player = playerAndUpdatedProps[0] as PhotonPlayer; ExitGames.Client.Photon.Hashtable props = playerAndUpdatedProps[1] as ExitGames.Client.Photon.Hashtable; if (player == null || props == null) { return; } if (!player.IsLocal && props.ContainsKey("CurrentScene")) { string playerNewScene = props["CurrentScene"] as string; if (!string.IsNullOrEmpty(playerNewScene)) { SetPlayerAvatarVisibility(player, playerNewScene.Equals(SceneManager.GetActiveScene().name, StringComparison.InvariantCultureIgnoreCase)); } } if (!player.IsLocal && props.ContainsKey("EnvironmentLocation") || player.CustomProperties.ContainsKey("EnvironmentPositionIndex")) { SetPlayerPosition(player); } }
/// <summary> /// creates a hashtable with only a few of the stats of a /// certain player /// </summary> protected virtual ExitGames.Client.Photon.Hashtable ExtractPlayerStats(vp_MPNetworkPlayer player, params string[] stats) { if (!PhotonNetwork.isMasterClient) return null; // create a player hashtable with only the given stats ExitGames.Client.Photon.Hashtable table = new ExitGames.Client.Photon.Hashtable(); //string str = "Extracting stats for player: " + vp_MPNetworkPlayer.GetName(player.ID); foreach (string s in stats) { object o = player.Stats.Get(s); if (o == null) { Debug.LogError("Error: (" + this + ") Player stat '" + s + "' could not be retrieved from player " + player.ID + "."); continue; } table.Add(s, o); //str += ": " + s + "(" + o + ")"; } //Debug.Log(str); return table; }
/// <summary> /// assembles a game state consisting of an individual array /// of stats extracted from each specified player. parameters /// 2 and up should be arrays of strings identifying the stats /// included for each respective player. the returned gamestate /// may include unique stat names for every player /// </summary> protected virtual ExitGames.Client.Photon.Hashtable AssembleGameStatePartial(int[] playerIDs, params string[][] stats) { if (playerIDs.Length != stats.Length) { Debug.Log("Error (" + this + ") Amount of playerIDs must be same as amount of playerStates."); return null; } ExitGames.Client.Photon.Hashtable state = new ExitGames.Client.Photon.Hashtable(); for (int v = 0; v < playerIDs.Length; v++) { if (state.ContainsKey(playerIDs[v])) // safety measure in case int array has duplicate id:s { Debug.LogWarning("Warning (" + this + ") Trying to add same player twice to a partial game state (not good). Duplicates will be ignored."); continue; } state.Add(playerIDs[v], ExtractPlayerStats(vp_MPNetworkPlayer.Get(playerIDs[v]), stats[v])); } return state; }
/// <summary> /// the game state can only be pushed out by the master client. /// however it is stored and kept in sync across clients in the /// form of the properties on the actual network players. /// in case a client becomes master it pushes out a new game /// state based on the network players in its own scene /// </summary> protected static ExitGames.Client.Photon.Hashtable AssembleGameState() { // NOTE: don't add custom integer keys, since ints are used // for player identification. for example, adding a key '5' // might result in a crash when player 5 tries to join. // adding string (or other type) keys should be fine if (!PhotonNetwork.isMasterClient) return null; vp_MPPlayerStats.EraseStats(); // NOTE: sending an RPC with a re-used gamestate will crash! we must create new gamestates every time vp_MPNetworkPlayer.RefreshPlayers(); ExitGames.Client.Photon.Hashtable state = new ExitGames.Client.Photon.Hashtable(); // -------- add game phase, game time and duration -------- state.Add("Phase", Phase); state.Add("TimeLeft", vp_MPClock.TimeLeft); state.Add("Duration", vp_MPClock.Duration); // -------- add the stats of all players (includes health) -------- foreach (vp_MPNetworkPlayer player in vp_MPNetworkPlayer.Players.Values) { if (player == null) continue; // add a player stats hashtable with the key 'player.ID' ExitGames.Client.Photon.Hashtable stats = player.Stats.All; if (stats != null) state.Add(player.ID, stats); } // -------- add the health of all non-player damagehandlers -------- foreach (vp_DamageHandler d in vp_DamageHandler.Instances.Values) { if (d is vp_PlayerDamageHandler) continue; if (d == null) continue; PhotonView p = d.GetComponent<PhotonView>(); if (p == null) continue; // add the view id for a damagehandler photon view, along with its health. // NOTE: we send and unpack the view id negative since some will potentially // be the same as existing player id:s in the hashtable (starting at 1) state.Add(-p.viewID, d.CurrentHealth); } // -------- add note of any disabled pickups -------- foreach (int id in vp_MPPickupManager.Instance.Pickups.Keys) { List<vp_ItemPickup> p; vp_MPPickupManager.Instance.Pickups.TryGetValue(id, out p); if ((p == null) || (p.Count < 1) || p[0] == null) continue; if (vp_Utility.IsActive(p[0].transform.gameObject)) continue; // there are two predicted cases were an ID might already be in the state: // 1) a player ID is the same as a pickup ID. this is highly unlikely since // player IDs start at 1 and pickup IDs are ~six figure numbers. also, // only currently disabled pickups are included in the state making it // even more unlikely // 2: a pickup has two vp_ItemPickup components with the same ID which is // the case with throwing weapons (grenades). this is highly likely, // but in this case it's fine to ignore the ID second time around if (!state.ContainsKey(id)) state.Add(id, false); } if (state.Count == 0) UnityEngine.Debug.LogError("Failed to get gamestate."); return state; }
public void RPCAddPlayerToGame( PhotonPlayer newPlayer ) { ExitGames.Client.Photon.Hashtable newProperties = new ExitGames.Client.Photon.Hashtable(); newProperties.Add("Ready", false); PhotonNetwork.player.SetCustomProperties( newProperties ); Debug.Log( "added player: " + newPlayer.name + " to game" ); }
/// <summary> /// Create a new room photon /// </summary> /// <param name="mInput"></param> /// <param name="MaxPlayers"></param> public void CreateRoom(InputField mInput) { //Avoid to request double connection. if (Joining) { Debug.Log("Already Request a connection, wait for server response."); return; } if (!String.IsNullOrEmpty(mInput.text)) { //Create hastable to send room information from lobby. ExitGames.Client.Photon.Hashtable roomOption = new ExitGames.Client.Photon.Hashtable(); //Add information in hashtable. roomOption[PropiertiesKeys.TimeRoomKey] = RoomTime[r_Time]; roomOption[PropiertiesKeys.RoomRoundKey] = GamePerRounds ? "1" : "0"; roomOption[PropiertiesKeys.SceneNameKey] = SceneManager[CurrentScene].SceneName; roomOption[PropiertiesKeys.RoomState] = "False"; string[] properties = new string[4]; properties[0] = PropiertiesKeys.RoomRoundKey; properties[1] = PropiertiesKeys.TimeRoomKey; properties[2] = PropiertiesKeys.SceneNameKey; properties[3] = PropiertiesKeys.RoomState; int mp = MaxPlayers[m_MaxPlayer]; PhotonNetwork.CreateRoom(mInput.text, new RoomOptions() { maxPlayers = (byte)mp , cleanupCacheOnLeave = true, customRoomProperties = roomOption, customRoomPropertiesForLobby = properties}, null); Joining = true; } else { Debug.Log("Room Name can not be empty!"); } }
void OnPhotonRandomJoinFailed() { // custom room properies. ExitGames.Client.Photon.Hashtable roomInfo = new ExitGames.Client.Photon.Hashtable(); CreateRoom(); }