private Client client; // Socket void Start() { this.client = GameObject.Find("Manager").GetComponent<ClientManager>().Client; user = User.Instance; if (user.is_connected) { PhotonNetwork.playerName = user.username; PhotonPeer.RegisterType(typeof(Team), (byte)'T', ObjectToByteArray, ByteToTeam); PhotonPeer.RegisterType(typeof(Composition), (byte)'C', ObjectToByteArray, ByteToComposition); PhotonPeer.RegisterType(typeof(Player), (byte)'P', ObjectToByteArray, ByteToPlayer); PhotonPeer.RegisterType(typeof(User), (byte)'U', ObjectToByteArray, ByteToUser); PhotonPeer.RegisterType(typeof(List<string>), (byte)'L', ObjectToByteArray, ByteToLS); PhotonHastable props = new PhotonHastable(); props.Add("Team", Settings.Instance.Selected_Team); props.Add("User", user); PhotonNetwork.player.SetCustomProperties(props); PhotonNetwork.ConnectUsingSettings(game_version_); this.room_name = user.username + "-" + rand.Next(1000); } }
/// <summary> /// Internally used to create players from event Join /// </summary> protected internal PhotonPlayer(bool isLocal, int actorID, Hashtable properties) { this.customProperties = new Hashtable(); this.isLocal = isLocal; this.actorID = actorID; this.InternalCacheProperties(properties); }
public void ClearTileClickEvForTurn(int turnToDelete) { Debug.Log("Clean Tile Click for Turn " + turnToDelete); Hashtable content = new Hashtable(); content[(byte)1] = turnToDelete; this.loadBalancingPeer.OpRaiseEvent(EvTileClick, content, true, new RaiseEventOptions() { CachingOption = EventCaching.RemoveFromRoomCache }); this.lastTilesClicked[turnToDelete].Clear(); }
/// <summary> /// Creates a player instance. /// To extend and replace this Player, override LoadBalancingPeer.CreatePlayer(). /// </summary> /// <param name="nickName">NickName of the player (a "well known property").</param> /// <param name="actorID">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param> /// <param name="isLocal">If this is the local peer's player (or a remote one).</param> /// <param name="playerProperties">A Hashtable of custom properties to be synced. Must use String-typed keys and serializable datatypes as values.</param> protected internal Player(string nickName, int actorID, bool isLocal, Hashtable playerProperties) { this.IsLocal = isLocal; this.actorID = actorID; this.NickName = nickName; this.CustomProperties = new Hashtable(); this.CacheProperties(playerProperties); }
public ParticlePlayer(string nickName, int actorID, bool isLocal, Hashtable actorProperties) : base(nickName, actorID, isLocal, actorProperties) { if (isLocal) { // we pick a random color when we create a local player this.RandomizeColor(); } }
protected internal Room(string roomName, Hashtable roomProperties, bool isVisible, bool isOpen, byte maxPlayers, string[] propsListedInLobby) : base(roomName, roomProperties) { // base sets name and (custom)properties. here we set "well known" properties this.isVisible = isVisible; this.isOpen = isOpen; this.maxPlayers = maxPlayers; this.PropsListedInLobby = propsListedInLobby; }
/// <summary> /// Don't use this method directly, unless you know how to cache and apply customActorProperties. /// The PhotonNetwork methods will handle player and room properties for you and call this method. /// </summary> public virtual bool OpCreateRoom(string roomName, RoomOptions roomOptions, TypedLobby lobby, Hashtable playerProperties, bool onGameServer) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpCreateRoom()"); } Dictionary<byte, object> op = new Dictionary<byte, object>(); if (!string.IsNullOrEmpty(roomName)) { op[ParameterCode.RoomName] = roomName; } if (lobby != null) { op[ParameterCode.LobbyName] = lobby.Name; op[ParameterCode.LobbyType] = (byte)lobby.Type; } if (onGameServer) { if (playerProperties != null && playerProperties.Count > 0) { op[ParameterCode.PlayerProperties] = playerProperties; op[ParameterCode.Broadcast] = true; // TODO: check if this also makes sense when creating a room?! // broadcast actor properties } if (roomOptions == null) { roomOptions = new RoomOptions(); } Hashtable gameProperties = new Hashtable(); op[ParameterCode.GameProperties] = gameProperties; gameProperties.MergeStringKeys(roomOptions.customRoomProperties); gameProperties[GameProperties.IsOpen] = roomOptions.isOpen; // TODO: check default value. dont send this then gameProperties[GameProperties.IsVisible] = roomOptions.isVisible; // TODO: check default value. dont send this then gameProperties[GameProperties.PropsListedInLobby] = roomOptions.customRoomPropertiesForLobby; if (roomOptions.maxPlayers > 0) { gameProperties[GameProperties.MaxPlayers] = roomOptions.maxPlayers; } if (roomOptions.cleanupCacheOnLeave) { op[ParameterCode.CleanupCacheOnLeave] = true; // this is actually setting the room's config gameProperties[GameProperties.CleanupCacheOnLeave] = true; // this is only informational for the clients which join } } // UnityEngine.Debug.Log("CreateGame: " + SupportClass.DictionaryToString(op)); return this.OpCustom(OperationCode.CreateGame, op, true); }
IEnumerator ProcessQueue( ) { var idx = 0; while ( AnnouncementQueue != null ) { //AnnouncementQueue[ idx ]; AnnouncementQueue = null; yield return null; } yield return null; }
/// <summary> /// Receive events from server /// </summary> /// <param name="eventCode"></param> /// <param name="content"></param> /// <param name="senderID"></param> public void OnEventCustom(byte eventCode, object content, int senderID) { Debug.Log(string.Format("OnEventRaised: {0}, {1}, {2}", eventCode, content, senderID)); Hashtable hash = new Hashtable(); hash = (Hashtable)content; switch (eventCode) { case EventID.LoadSyncLevel: string s = (string)hash["Level"]; NextLevel = s; InvokeRepeating("InvokeLoad", 1, 1); break; case EventID.PlayerJoinPre: // break; } }
/// <summary> /// Don't use this method directly, unless you know how to cache and apply customActorProperties. /// The PhotonNetwork methods will handle player and room properties for you and call this method. /// </summary> public virtual bool OpCreateRoom(string gameID, bool isVisible, bool isOpen, byte maxPlayers, bool autoCleanUp, Hashtable customGameProperties, Hashtable customPlayerProperties, string[] customRoomPropertiesForLobby) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpCreateRoom()"); } Hashtable gameProperties = new Hashtable(); gameProperties[GameProperties.IsOpen] = isOpen; gameProperties[GameProperties.IsVisible] = isVisible; gameProperties[GameProperties.PropsListedInLobby] = customRoomPropertiesForLobby; gameProperties.MergeStringKeys(customGameProperties); if (maxPlayers > 0) { gameProperties[GameProperties.MaxPlayers] = maxPlayers; } Dictionary<byte, object> op = new Dictionary<byte, object>(); op[ParameterCode.GameProperties] = gameProperties; op[ParameterCode.Broadcast] = true; if (customPlayerProperties != null) { op[ParameterCode.PlayerProperties] = customPlayerProperties; } if (!string.IsNullOrEmpty(gameID)) { op[ParameterCode.RoomName] = gameID; } // server's default is 'false', so we actually only need to send this when 'true' if (autoCleanUp) { op[ParameterCode.CleanupCacheOnLeave] = autoCleanUp; gameProperties[GameProperties.CleanupCacheOnLeave] = autoCleanUp; } return this.OpCustom(OperationCode.CreateGame, op, true); }
public override void OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps) { Debug.Log("OnPlayerPropertiesUpdate"); object characterID_Obj; if (changedProps.TryGetValue("PERSONAGEM", out characterID_Obj)) { int characterID = (int)characterID_Obj; if (characterID > 0) { foreach (Transform item in transform) { if (item.GetComponent <CanvasCharacter>().id == characterID) { item.GetComponent <CanvasCharacter>().SelectCharacter(targetPlayer.NickName, targetPlayer.ActorNumber); } } } } }
private void startNewRound(int drawerInitId) { var randomWordForRoom = loadRandomWord(); //Random Word for everyone ExitGames.Client.Photon.Hashtable randomWordProp = new ExitGames.Client.Photon.Hashtable { { MultiPlayerGame.RANDOM_WORD, randomWordForRoom } }; PhotonNetwork.CurrentRoom.SetCustomProperties(randomWordProp); ExitGames.Client.Photon.Hashtable newDrawer = new ExitGames.Client.Photon.Hashtable { { MultiPlayerGame.DRAWER, drawerInitId } }; PhotonNetwork.CurrentRoom.SetCustomProperties(newDrawer); ErrorBox.SetActive(false); //Set drawer ExitGames.Client.Photon.Hashtable drawerProp = new ExitGames.Client.Photon.Hashtable { { MultiPlayerGame.DRAWER, drawerInitId } }; PhotonNetwork.CurrentRoom.SetCustomProperties(drawerProp); //Debug.Log("A new round has started!"); var localId = PhotonNetwork.LocalPlayer.ActorNumber - 1; var drawer = Convert.ToInt16(PhotonNetwork.CurrentRoom.CustomProperties["Drawer"]); var drawerId = drawer; //Set the amount text if (PhotonNetwork.CurrentRoom.PlayerCount > 1) { Amount.text = PhotonNetwork.CurrentRoom.PlayerCount + " people are in the game"; } else { Amount.text = PhotonNetwork.CurrentRoom.PlayerCount + " person is in te game"; } }
//매치테이블을 셋팅 private IEnumerator SetProfileCorutine() { //커스텀 프로퍼티를 가져오는데 값이 null이나 ""이면 충분히 기다리지 않았다는 뜻. yield return(new WaitForSeconds(0.1f)); Debug.Log("setProfile"); if (PhotonNetwork.InRoom) { Debug.Log("in room"); } else { Debug.Log("out room"); } int A_TeamProfileIndex = 0; int B_TeamProfileIndex = 0; foreach (var player in PhotonNetwork.PlayerList) { Debug.Log("참가한 플레이어 이름" + player.NickName); ExitGames.Client.Photon.Hashtable properties = player.CustomProperties; if ((int)properties["team"] == 0) { A_TeamProfileIndex = Mathf.Clamp(A_TeamProfileIndex, 0, A_TeamProfiles.Length); A_TeamNames[A_TeamProfileIndex].text = player.NickName; A_TeamPortraits[A_TeamProfileIndex++].sprite = portraitDic[(string)properties["character"]]; } else { B_TeamProfileIndex = Mathf.Clamp(B_TeamProfileIndex, 0, B_TeamProfiles.Length); B_TeamNames[B_TeamProfileIndex].text = player.NickName; Debug.Log(player.NickName + "의 캐릭터: " + (string)properties["character"]); B_TeamPortraits[B_TeamProfileIndex++].sprite = portraitDic[(string)properties["character"]]; } } }
void Update() { if (!startTimer) { return; } timerIncrementValue = PhotonNetwork.Time - startTime; if (timerIncrementValue >= 10.0f && timerIncrementValue <= 60.0f) { spawnMgr.SetActive(true); } else if (timerIncrementValue >= 60.0f && timerIncrementValue <= 65.0f) { spawnMgr.SetActive(false); BOSS.SetActive(true); // boss_tr.Translate(new Vector3(0.0f, 5.0f, 0.0f) * 25 * Time.deltaTime); boss_tr.position = Vector3.Lerp(boss_tr.position, new Vector3(0, 0, 550), Time.deltaTime * 1.0f); } else if (timerIncrementValue > 65.0f) { bossPattern(); } if (PhotonNetwork.IsMasterClient) { gen_RanValues(); RandomValue = new ExitGames.Client.Photon.Hashtable(); RandomValue.Add("Random", init_str); PhotonNetwork.CurrentRoom.SetCustomProperties(RandomValue); set_RanValues(); } else { init_str = PhotonNetwork.CurrentRoom.CustomProperties["Random"].ToString(); set_RanValues(); } }
void EquipItem(int _index) { if (_index == previousItemIndex) { return; } if (currentWeapon != null) { Destroy(currentWeapon); } itemIndex = _index; currentIndex = _index; GameObject t_newweapon = Instantiate(gunitems[itemIndex].gunPrefab, itemHolder.position, itemHolder.rotation, itemHolder) as GameObject; t_newweapon.transform.localPosition = Vector3.zero; t_newweapon.transform.localEulerAngles = Vector3.zero; currentWeapon = t_newweapon; //if (previousItemIndex != -1) //{ // Debug.Log("Inside previousItemIndex:" + previousItemIndex); // Destroy(gunitems[previousItemIndex].gunPrefab); //} //Debug.Log("Inside previousItemIndex:" + itemIndex); //previousItemIndex = itemIndex; if (PV.IsMine) { Hashtable hash = new Hashtable(); hash.Add("itemIndex", itemIndex); PhotonNetwork.LocalPlayer.SetCustomProperties(hash); } }
private IEnumerator Pass1Sec(float waitTime) { yield return(new WaitForSeconds(waitTime)); currentTime++; int time = (gameState == GameState.Drawing) ? roundTime - currentTime : currentTime - betweenRoundsTime; ExitGames.Client.Photon.Hashtable roomProperties = new ExitGames.Client.Photon.Hashtable(); roomProperties.Add("time", time); PhotonNetwork.room.SetCustomProperties(roomProperties); HUDController.Instance.UpdateTime(time); NetworkController.Instance.PassTime(time); if (gameState == GameState.Drawing) { if (currentTime >= roundTime) { EndRound(); NetworkController.Instance.NextRound(); } else { StartCoroutine(Pass1Sec(1f)); } } else if (gameState == GameState.WaitingForNextRound) { if (currentTime >= betweenRoundsTime) { StartDrawing(); } else { StartCoroutine(Pass1Sec(1f)); } } }
/**在队伍面板显示玩家信息 * 函数参数表示是否显示本地玩家信息 */ void UpdateTeamPanel(bool isUpdateSelf) { GameObject go; foreach (PhotonPlayer p in PhotonNetwork.playerList) //获取房间里所有玩家信息 { if (!isUpdateSelf && p.isLocal) { continue; //判断是否更新本地玩家信息 } costomProperties = p.customProperties; //获取玩家自定义属性 if (costomProperties ["Team"].Equals("Team1")) //判断玩家所属队伍 { go = Team1 [(int)costomProperties ["TeamNum"]]; //查询玩家的队伍序号 go.SetActive(true); //激活显示玩家信息的UI texts = go.GetComponentsInChildren <Text> (); //获取显示玩家信息的Text组件 } else { go = Team2 [(int)costomProperties ["TeamNum"]]; go.SetActive(true); texts = go.GetComponentsInChildren <Text> (); } texts [0].text = p.name; //显示玩家姓名 if (p.isMasterClient) //如果玩家是MasterClient { texts[1].text = "Host"; //玩家状态显示"房主" } else if ((bool)costomProperties ["isReady"]) //如果玩家不是MasterClient,获取玩家的准备状态isReady { texts [1].text = "Ready"; //isReady为true,显示"已准备" } else { texts [1].text = "Unready"; //isReady为false,显示"未准备" } } }
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"); } }
// Use this for initialization void Start() { instance = this; gameplay.SetActive(false); GameController.Instance.firstPlayerPoints = firstPlayerPoints; if (PhotonNetwork.playerList.Length > 1) { startGameButton.gameObject.SetActive(false); GameController.Instance.playerDrawing = NetworkController.GetPhotonPlayerFromID((int)PhotonNetwork.room.customProperties["playerDrawingID"]); } else { GameController.isHost = true; startGameButton.isEnabled = false; ExitGames.Client.Photon.Hashtable roomProperties = new ExitGames.Client.Photon.Hashtable(); roomProperties.Add("playerDrawingID", PhotonNetwork.player.ID); roomProperties.Add("time", 0); PhotonNetwork.room.SetCustomProperties(roomProperties); GameController.Instance.playerDrawing = PhotonNetwork.player; } //set all player proterties ExitGames.Client.Photon.Hashtable playerProperties = new ExitGames.Client.Photon.Hashtable(); playerProperties.Add("guessed", false); playerProperties.Add("points", 0); playerProperties.Add("drawing", PhotonNetwork.playerList.Length == 1); playerProperties.Add("justEntered", true); playerProperties.Add("title", "No Title Yet"); //playerProperties.Add ("avatar", "avataor001"); PhotonNetwork.player.SetCustomProperties(playerProperties); ArrangePlayers(); }
void OnJoinedRoom() { RoomUI.SetActive(true); if (PhotonNetwork.room.PlayerCount == 1) { PhotonHashtable Player = new PhotonHashtable() { { "player", "P1" } }; PhotonNetwork.player.SetCustomProperties(Player); PhotonNetwork.player.NickName = "Player 1"; } else if (PhotonNetwork.room.PlayerCount == 2) { PhotonHashtable Player = new PhotonHashtable() { { "player", "P2" } }; PhotonNetwork.player.SetCustomProperties(Player); PhotonNetwork.player.NickName = "Player 2"; } else if (PhotonNetwork.room.PlayerCount == 3) { PhotonHashtable Player = new PhotonHashtable() { { "player", "P3" } }; PhotonNetwork.player.SetCustomProperties(Player); PhotonNetwork.player.NickName = "Player 3"; } if (PhotonNetwork.isMasterClient) { print("you are master client, waiting for full amount of players to start the game"); checkGameStart = true; } }
void UpdateTeamPanel(bool isUpdateSelf) { GameObject go; foreach (PhotonPlayer p in PhotonNetwork.playerList) { if (!isUpdateSelf && p.IsLocal) { continue; } costomProperties = p.CustomProperties; if (costomProperties["Team"].Equals("Team1")) { go = Team1[(int)costomProperties["TeamNum"]]; go.SetActive(true); texts = go.GetComponentsInChildren <Text>(); } else { go = Team2[(int)costomProperties["TeamNum"]]; go.SetActive(true); texts = go.GetComponentsInChildren <Text>(); } texts[0].text = p.name; if (p.IsMasterClient) { texts[1].text = "Master"; } else if ((bool)costomProperties["isReady"]) { texts[1].text = "is Ready"; } else { texts[1].text = "Not Readye"; } } }
/// <summary> /// Spawn Player Function /// </summary> /// <param name="t_team"></param> public void SpawnPlayer(Team t_team) { if (OurPlayer != null) { PhotonNetwork.Destroy(OurPlayer); } Hashtable PlayerTeam = new Hashtable(); PlayerTeam.Add("Team", t_team.ToString()); PhotonNetwork.player.SetCustomProperties(PlayerTeam); if (t_team == Team.Recon) { OurPlayer = PhotonNetwork.Instantiate(Player_Team_1.name, GetSpawn(ReconSpawnPoint), Quaternion.identity, 0); } else if (t_team == Team.Delta) { OurPlayer = PhotonNetwork.Instantiate(Player_Team_2.name, GetSpawn(DeltaSpawnPoint), Quaternion.identity, 0); } else { OurPlayer = PhotonNetwork.Instantiate(Player_Team_1.name, GetSpawn(AllSpawnPoints), Quaternion.identity, 0); } this.GetComponent <bl_ChatRoom>().AddLine("Spawn in " + t_team.ToString() + " Team"); this.GetComponent <bl_ChatRoom>().Refresh(); m_RoomCamera.gameObject.SetActive(false); if (mOverlayCanvas != null) { Camera cam = GameObject.FindWithTag("WeaponCam").GetComponent <Camera>(); mOverlayCanvas.worldCamera = cam; } StartCoroutine(bl_RoomMenu.FadeOut(1)); Screen.lockCursor = true; }
public void joinRoom() { if (PhotonNetwork.IsConnected) { PhotonNetwork.LocalPlayer.NickName = playerName; Debug.Log("Photon connected|trying to join room" + roomNameInput.text); RoomOptions roomOptions = new RoomOptions(); //CustomProperties hashtablesetup ExitGames.Client.Photon.Hashtable RoomCustomProperties = new ExitGames.Client.Photon.Hashtable(); //Custom room properties are private until set in custom room props for lobby RoomCustomProperties.Add("player", "john smith"); RoomCustomProperties.Add(RoomPropety.Scenario, "FreestyleAuditorium"); RoomCustomProperties.Add(RoomPropety.Company, "Instage"); RoomCustomProperties.Add(RoomPropety.Location, "somewhere"); //This chooses what custom room properties are public values roomOptions.CustomRoomProperties = RoomCustomProperties; string[] publicProperties = { RoomPropety.Scenario, RoomPropety.Company, RoomPropety.Location }; roomOptions.CustomRoomPropertiesForLobby = publicProperties; //TypedLobby typedLobby = new TypedLobby(roomName, LobbyType.Default); PhotonNetwork.JoinOrCreateRoom(roomName, roomOptions, TypedLobby.Default); //Debug.Log(PhotonNetwork.CurrentRoom.CustomProperties.ContainsKey("player").ToString()); } }
private void Start() { if (view.IsMine == false) { if (view.Owner.CustomProperties.ContainsKey("Health") == false) { Health = playSettings.initialHealth; Shield = true; } else { Health = (int)view.Owner.CustomProperties["Health"]; } return; } ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable(); hash.Add("Health", playSettings.initialHealth); PhotonNetwork.LocalPlayer.SetCustomProperties(hash); Shield = true; }
public void onClickCreate() { //host = true; // player_num = "player1"; // random pin number every time PIN.text = Random.Range(1000, 9999).ToString(); string password = PIN.text; RoomOptions roomoptions = new RoomOptions(); roomoptions.MaxPlayers = 4; string[] roompropsInLobby = { "gm" }; // game mode //party game mode //1. 丢纸团 = tp //2. 转盘= roll //3。 摇可乐 = shake ExitGames.Client.Photon.Hashtable customesproperties = new ExitGames.Client.Photon.Hashtable(); roomoptions.CustomRoomPropertiesForLobby = roompropsInLobby; roomoptions.CustomRoomProperties = customesproperties; PhotonNetwork.CreateRoom(password, roomoptions); // create_join_panel.SetActive(false); // RoomPanel.SetActive(true); //setPlayerName(player_num, PhotonNetwork.LocalPlayer.NickName); }
/// <summary> /// Caches custom properties for this player. /// </summary> internal void InternalCacheProperties(Hashtable properties) { if (properties == null || properties.Count == 0 || this.customProperties.Equals(properties)) { return; } if (properties.ContainsKey(ActorProperties.PlayerName)) { this.nameField = (string)properties[ActorProperties.PlayerName]; } if (properties.ContainsKey(ActorProperties.UserId)) { this.userId = (string)properties[ActorProperties.UserId]; } if (properties.ContainsKey(ActorProperties.IsInactive)) { this.isInactive = (bool)properties[ActorProperties.IsInactive]; //TURNBASED new well-known propery for players } this.customProperties.MergeStringKeys(properties); this.customProperties.StripKeysWithNullValues(); }
void Start() { bonusRoundInformPanelGameObject.SetActive(false); GetComponent <BonusRound>().enabled = false; scoreDictionary.Add("RegularPopcorn", 1); //scoreDictionary.Add("Cookie", 3); scoreDictionary.Add("BananaPeel", -5); scoreDictionary.Add("Donut", 3); scoreDictionary.Add("ChocolatePopcorn", 1); scoreDictionary.Add("MatchaPopcorn", 1); scoreDictionary.Add("StrawberryPopcorn", 1); scoreDictionary.Add("HoneyPopcorn", 1); spawnManager.enabled = false; if (!StartSceneLauncher._instance.singlePlayerMode) { scoreHash = new Hashtable(); PhotonNetwork.LocalPlayer.SetCustomProperties(scoreHash); } GameStart(); countDownPanel.SetActive(false); }
private void sendChangeMC(int targetId) { Type type = typeof(PhotonNetwork); //FieldInfo networkingPeerField = type.GetField("networkingPeer", BindingFlags.Static | BindingFlags.Public); //object networkingPeer = networkingPeerField.GetValue(null); //MethodInfo raiseOpMethod = networkingPeer.GetType().GetMethod("OpRaiseEvent", BindingFlags.Public | BindingFlags.Instance); ExitGames.Client.Photon.Hashtable table = new ExitGames.Client.Photon.Hashtable(); RaiseEventOptions opts = new RaiseEventOptions(); table[1] = PhotonNetwork.player.ID; opts.TargetActors = new int[] { targetId }; opts.Receivers = ExitGames.Client.Photon.Lite.ReceiverGroup.All; // opts.CachingOption = ExitGames.Client.Photon.Lite.EventCaching.AddToRoomCache; try { PhotonNetwork.networkingPeer.OpRaiseEvent(208, table, true, opts); //raiseOpMethod.Invoke(networkingPeer, new object[] { (byte)208, table, true, opts }); } catch (Exception e) { ModMain.instance.log(e); } }
// ロビーに入ると呼ばれる void OnJoinedLobby() { Debug.Log("ロビーに入りました。"); if (mode == 1) { // ランダムにルームに入室する ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "mode", 1 } }; PhotonNetwork.JoinRandomRoom(expectedCustomRoomProperties, 2); } else if (mode == 3) { // ルームに入室する ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "mode", 3 }, { "key", key } }; PhotonNetwork.JoinRandomRoom(expectedCustomRoomProperties, 2); } }
public void CreateRoom() { if (PhotonNetwork.connected) { Debug.Log("Create room"); if (GameManager.instance.isDirector) { PhotonNetwork.CreateRoom("MainRoom" + Random.value.ToString(), new RoomOptions() { maxPlayers = 20 }, TypedLobby.Default); } else { PhotonNetwork.playerName = ClientManager.instance.inputName.label.text; ExitGames.Client.Photon.Hashtable props = new ExitGames.Client.Photon.Hashtable(); props.Add("type", (int)ClientManager.instance.currentUType); props.Add("door", (int)ClientManager.instance.currentDoor); PhotonNetwork.player.SetCustomProperties(props); PhotonNetwork.JoinRandomRoom(); } } }
public void EndRound() { gameState = GameState.WaitingForNextRound; StopAllCoroutines(); canDraw = false; isHost = false; playerDrawing = nextPlayerDrawing; nextPlayerDrawing = GetNextPlayerForDrawing(playerDrawing); ExitGames.Client.Photon.Hashtable roomProperties = new ExitGames.Client.Photon.Hashtable(); roomProperties.Add("playerDrawingID", playerDrawing.ID); roomProperties.Add("nextPlayerDrawingID", nextPlayerDrawing.ID); PhotonNetwork.room.SetCustomProperties(roomProperties); NetworkController.Instance.SendNewNextPlayerToDraw(playerDrawing); GameController.Instance.playerDrawing = PhotonNetwork.player; HUDController.Instance.HideLetters(); HUDController.Instance.HideColors(); }
public void Rank(int i) { if (topRankhand.Length >= 3) { topRankhand = new int[0] { }; } System.Array.Resize(ref topRankhand, topRankhand.Length + 1); topRankhand[topRankhand.Length - 1] = i; if (topRankhand.Length == 3) { int j; for (j = 0; j < topRankhand.Length; j++) { var properties = new ExitGames.Client.Photon.Hashtable(); string card = PhotonNetwork.player.ID + "topRankhand" + j; properties.Add(card, topRankhand[j]); PhotonNetwork.room.SetCustomProperties(properties); Debug.Log(card + topRankhand[j]); } } }
public void Setup(ExitGames.Client.Photon.Hashtable rProperties) { foreach (var keyobj in rProperties.Keys) { if (Enum.TryParse((string)keyobj, out RPKey rpkey)) { object vall; switch (rpkey) { case RPKey.SyncType: //Debug.Log($"SyncType {rProperties[keyobj]}"); vall = TransformSyncType.SerializeViewCurrent; rProperties.TryGetValue(keyobj, out vall); SetTransformSyncType((TransformSyncType)vall); break; default: break; } } } }
public override void OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps) { if (changedProps.ContainsKey("indicator")) { var indicator = Instantiate(this.indicator, Vector3.zero, Quaternion.identity); var indicatorScript = indicator.GetComponent <PlayerIndicator>(); indicatorScript.camera = camera.GetComponent <PlayerCamera>().camera; indicatorScript.username = targetPlayer.NickName; indicatorScript.color = colorMap[changedProps["indicator"].ToString()].color; foreach (MultiCar car in FindObjectsOfType <MultiCar>()) { if (car.GetActorNumber() == targetPlayer.ActorNumber) { indicator.transform.SetParent(car.transform); indicatorScript.target = car.transform; break; } } return; } CheckGameOver(changedProps, targetPlayer); }
public void ChangeToQueue() { ExitGames.Client.Photon.Hashtable hash = new ExitGames.Client.Photon.Hashtable(); hash = PhotonNetwork.LocalPlayer.CustomProperties; int Team = (int)hash["Team"]; if (Team != -1) { hash.Remove("Team"); hash.Add("Team", -1); PhotonNetwork.LocalPlayer.CustomProperties = hash; } bool IsReady = (bool)PhotonNetwork.LocalPlayer.CustomProperties["ReadyToPlay"]; if (IsReady) { hash.Remove("ReadyToPlay"); hash.Add("ReadyToPlay", false); PhotonNetwork.LocalPlayer.CustomProperties = hash; } }
public static void NextTurn(this Room room) { if (room == null) { Debug.LogError("Check if client is in room or is connected."); Debug.Break(); } Hashtable roomProps = new Hashtable(); int turn = 0; if (room.CustomProperties.ContainsKey(TurnCountKey)) { turn = (int)room.CustomProperties[TurnCountKey]; } turn++; // Set Turn roomProps.Add(TurnCountKey, turn); // Set start of Turn roomProps.Add(TurnStartKey, PhotonNetwork.ServerTimestamp); room.SetCustomProperties(roomProps); }
public void SaveMyCardProperties() { if (myPlayer == null) { return; } if (!isBot && !isMine) { return; } ExitGames.Client.Photon.Hashtable properties = myPlayer.CustomProperties; properties[PhotonEnums.Player.HandRank] = (int)_playerHandRank; properties[PhotonEnums.Player.ValueHand] = valueHand; properties[PhotonEnums.Player.SecondValueHand] = secondValueHand; properties[PhotonEnums.Player.RankPoker] = RANK; properties[PhotonEnums.Player.Kicker] = _kicker; properties[PhotonEnums.Player.SecondKicker] = secondKicker; myPlayer.SetCustomProperties(properties); }
public void AssignPlayer() { int slot_index = PhotonUtility.GetPlayerProperties <int> (PhotonNetwork.player, PhotonEnums.Player.SlotIndex); if (slot_index == -1) { PhotonUtility.SetPlayerProperties(PhotonNetwork.player, PhotonEnums.Player.SlotIndex, GetAvailableRoomSlotIndex()); return; } //Check whether the game is already started ExitGames.Client.Photon.Hashtable playerProperties = PhotonNetwork.player.CustomProperties; playerProperties[PhotonEnums.Player.ContentURL] = PlayerData.costume_id; playerProperties[PhotonEnums.Player.PlayerID] = PlayerData.id; playerProperties[PhotonEnums.Player.IsBot] = false; playerProperties[PhotonEnums.Player.Name] = PlayerData.display_name; playerProperties[PhotonEnums.Player.Gender] = 0; playerProperties[PhotonEnums.Player.PictureURL] = string.Empty; PhotonNetwork.player.SetCustomProperties(playerProperties); objPlayers[slot_index].photonView.TransferOwnership(PhotonNetwork.player); objPlayers[slot_index].Initiate(); }
/// <summary> /// get the current time and verify if it is correct /// </summary> void GetTime() { RoundDuration = (int)PhotonNetwork.room.CustomProperties[PropiertiesKeys.TimeRoomKey]; if (PhotonNetwork.isMasterClient) { m_Reference = (float)PhotonNetwork.time; Hashtable startTimeProp = new Hashtable(); // only use ExitGames.Client.Photon.Hashtable for Photon startTimeProp.Add(StartTimeKey, m_Reference); PhotonNetwork.room.SetCustomProperties(startTimeProp); } else { if (PhotonNetwork.room.CustomProperties.ContainsKey(StartTimeKey)) { m_Reference = (float)PhotonNetwork.room.CustomProperties[StartTimeKey]; if (!UI.TimeUI.activeSelf) { UI.TimeUI.SetActive(true); } } } }
public override void OnRoomPropertiesUpdate(ExitGames.Client.Photon.Hashtable propertiesThatChanged) { Debug.Log("test" + propertiesThatChanged); if (propertiesThatChanged.Count == 8) { bool leaderboardInit = true; for (int i = 0; i < 4; i++) { string key = "leaderboardSlot" + (i + 1); if (!propertiesThatChanged.ContainsKey(key)) { leaderboardInit = false; break; } } if (leaderboardInit) { CreatePlayer(); } } }
public bool OpSetCustomPropertiesOfRoom(Hashtable gameProperties, bool broadcast, byte channelId) { return this.OpSetPropertiesOfRoom(gameProperties.StripToStringKeys(), expectedProperties: null, webForward: false); }
/// <summary> /// Operation to join a random, available room. Overloads take additional player properties. /// This is an async request which triggers a OnOperationResponse() call. /// If all rooms are closed or full, the OperationResponse will have a returnCode of ErrorCode.NoRandomMatchFound. /// If successful, the OperationResponse contains a gameserver address and the name of some room. /// </summary> /// <returns>If the operation could be sent currently (requires connection).</returns> public virtual bool OpJoinRandomRoom(OpJoinRandomRoomParams opJoinRandomRoomParams) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpJoinRandomRoom()"); } Hashtable expectedRoomProperties = new Hashtable(); expectedRoomProperties.MergeStringKeys(opJoinRandomRoomParams.ExpectedCustomRoomProperties); if (opJoinRandomRoomParams.ExpectedMaxPlayers > 0) { expectedRoomProperties[GamePropertyKey.MaxPlayers] = opJoinRandomRoomParams.ExpectedMaxPlayers; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); if (expectedRoomProperties.Count > 0) { opParameters[ParameterCode.GameProperties] = expectedRoomProperties; } if (opJoinRandomRoomParams.MatchingType != MatchmakingMode.FillRoom) { opParameters[ParameterCode.MatchMakingType] = (byte) opJoinRandomRoomParams.MatchingType; } if (opJoinRandomRoomParams.TypedLobby != null && !string.IsNullOrEmpty(opJoinRandomRoomParams.TypedLobby.Name)) { opParameters[ParameterCode.LobbyName] = opJoinRandomRoomParams.TypedLobby.Name; opParameters[ParameterCode.LobbyType] = (byte) opJoinRandomRoomParams.TypedLobby.Type; } if (!string.IsNullOrEmpty(opJoinRandomRoomParams.SqlLobbyFilter)) { opParameters[ParameterCode.Data] = opJoinRandomRoomParams.SqlLobbyFilter; } if (opJoinRandomRoomParams.ExpectedUsers != null && opJoinRandomRoomParams.ExpectedUsers.Length > 0) { opParameters[ParameterCode.Add] = opJoinRandomRoomParams.ExpectedUsers; } // UnityEngine.Debug.LogWarning("OpJoinRandom: " + opParameters.ToStringFull()); return this.OpCustom(OperationCode.JoinRandomGame, opParameters, true); }
public bool OpSetCustomPropertiesOfActor(int actorNr, Hashtable actorProperties) { return this.OpSetPropertiesOfActor(actorNr, actorProperties.StripToStringKeys(), null); }
protected internal void SetSceneInProps() { if (PhotonNetwork.isMasterClient) { Hashtable setScene = new Hashtable(); setScene[NetworkingPeer.CurrentSceneProperty] = Application.loadedLevelName; //PhotonNetwork.room.SetCustomProperties(setScene); } }
/// <summary> /// Called when a room's custom properties changed. The propertiesThatChanged contains all that was set via Room.SetCustomProperties. /// </summary> /// <remarks> /// Since v1.25 this method has one parameter: Hashtable propertiesThatChanged.<br/> /// Changing properties must be done by Room.SetCustomProperties, which causes this callback locally, too. /// </remarks> /// <param name="propertiesThatChanged"></param> public virtual void OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged) { }
protected void OpSetPropertyOfRoom(byte propCode, object value) { Hashtable properties = new Hashtable(); properties[propCode] = value; this.OpSetPropertiesOfRoom(properties, expectedProperties: null, webForward: false); }
// calls OnPhotonSerializeView (through ExecuteOnSerialize) // the content created here is consumed by receivers in: ReadOnSerialize private Hashtable OnSerializeWrite(PhotonView view) { PhotonStream pStream = new PhotonStream( true, null ); PhotonMessageInfo info = new PhotonMessageInfo( this.mLocalActor, this.ServerTimeInMilliSeconds, view ); // each view creates a list of values that should be sent view.SerializeView( pStream, info ); if( pStream.Count == 0 ) { return null; } object[] dataArray = pStream.data.ToArray(); if (view.synchronization == ViewSynchronization.UnreliableOnChange) { if (AlmostEquals(dataArray, view.lastOnSerializeDataSent)) { if (view.mixedModeIsReliable) { return null; } view.mixedModeIsReliable = true; view.lastOnSerializeDataSent = dataArray; } else { view.mixedModeIsReliable = false; view.lastOnSerializeDataSent = dataArray; } } // EVDATA: // 0=View ID (an int, never compressed cause it's not in the data) // 1=data of observed type (different per type of observed object) // 2=compressed data (in this case, key 1 is empty) // 3=list of values that are actually null (if something was changed but actually IS null) Hashtable evData = new Hashtable(); evData[(byte)0] = (int)view.viewID; evData[(byte)1] = dataArray; // this is the actual data (script or observed object) if (view.synchronization == ViewSynchronization.ReliableDeltaCompressed) { // compress content of data set (by comparing to view.lastOnSerializeDataSent) // the "original" dataArray is NOT modified by DeltaCompressionWrite // if something was compressed, the evData key 2 and 3 are used (see above) bool somethingLeftToSend = this.DeltaCompressionWrite(view, evData); // buffer the full data set (for next compression) view.lastOnSerializeDataSent = dataArray; if (!somethingLeftToSend) { return null; } } return evData; }
private Hashtable GetActorPropertiesForActorNr(Hashtable actorProperties, int actorNr) { if (actorProperties.ContainsKey(actorNr)) { return (Hashtable)actorProperties[actorNr]; } return actorProperties; }
private void SendPlayerName() { if (this.State == global::PeerState.Joining) { // this means, the join on the gameServer is sent (with an outdated name). send the new when in game this.mPlayernameHasToBeUpdated = true; return; } if (this.mLocalActor != null) { this.mLocalActor.name = this.PlayerName; Hashtable properties = new Hashtable(); properties[ActorProperties.PlayerName] = this.PlayerName; if (this.mLocalActor.ID > 0) { this.OpSetPropertiesOfActor(this.mLocalActor.ID, properties, true, (byte)0); this.mPlayernameHasToBeUpdated = false; } } }
protected internal void SetLevelInPropsIfSynced(object levelId) { if (!PhotonNetwork.automaticallySyncScene || !PhotonNetwork.isMasterClient || PhotonNetwork.room == null) { return; } if (levelId == null) { Debug.LogError("Parameter levelId can't be null!"); return; } // check if "current level" is already set in props if (PhotonNetwork.room.customProperties.ContainsKey(NetworkingPeer.CurrentSceneProperty)) { object levelIdInProps = PhotonNetwork.room.customProperties[NetworkingPeer.CurrentSceneProperty]; if (levelIdInProps is int && Application.loadedLevel == (int)levelIdInProps) { return; } if (levelIdInProps is string && Application.loadedLevelName.Equals((string)levelIdInProps)) { return; } } // current level is not yet in props, so this client has to set it Hashtable setScene = new Hashtable(); if (levelId is int) setScene[NetworkingPeer.CurrentSceneProperty] = (int)levelId; else if (levelId is string) setScene[NetworkingPeer.CurrentSceneProperty] = (string)levelId; else Debug.LogError("Parameter levelId must be int or string!"); PhotonNetwork.room.SetCustomProperties(setScene); this.SendOutgoingCommands(); // send immediately! because: in most cases the client will begin to load and not send for a while }
// gameID can be null (optional). The server assigns a unique name if no name is set // joins a room and sets your current username as custom actorproperty (will broadcast that) #endregion #region Helpers private void ReadoutProperties(Hashtable gameProperties, Hashtable pActorProperties, int targetActorNr) { // Debug.LogWarning("ReadoutProperties gameProperties: " + gameProperties.ToStringFull() + " pActorProperties: " + pActorProperties.ToStringFull() + " targetActorNr: " + targetActorNr); // read game properties and cache them locally if (this.mCurrentGame != null && gameProperties != null) { this.mCurrentGame.CacheProperties(gameProperties); SendMonoMessage(PhotonNetworkingMessage.OnPhotonCustomRoomPropertiesChanged, gameProperties); if (PhotonNetwork.automaticallySyncScene) { this.LoadLevelIfSynced(); // will load new scene if sceneName was changed } } if (pActorProperties != null && pActorProperties.Count > 0) { if (targetActorNr > 0) { // we have a single entry in the pActorProperties with one // user's name // targets MUST exist before you set properties PhotonPlayer target = this.GetPlayerWithID(targetActorNr); if (target != null) { Hashtable props = this.GetActorPropertiesForActorNr(pActorProperties, targetActorNr); target.InternalCacheProperties(props); SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, target, props); } } else { // in this case, we've got a key-value pair per actor (each // value is a hashtable with the actor's properties then) int actorNr; Hashtable props; string newName; PhotonPlayer target; foreach (object key in pActorProperties.Keys) { actorNr = (int)key; props = (Hashtable)pActorProperties[key]; newName = (string)props[ActorProperties.PlayerName]; target = this.GetPlayerWithID(actorNr); if (target == null) { target = new PhotonPlayer(false, actorNr, newName); this.AddNewPlayer(actorNr, target); } target.InternalCacheProperties(props); SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, target, props); } } } }
/// <summary> /// reads incoming messages created by "OnSerialize" /// </summary> private bool DeltaCompressionRead(PhotonView view, Hashtable data) { if (data.ContainsKey((byte)1)) { // we have a full list of data (cause key 1 is used), so return "we have uncompressed all" return true; } // Compression was applied as data[(byte)2] exists (this is the data with some fields being compressed to null) // now we also need a previous "full" list of values to restore values that are null in this msg if (view.lastOnSerializeDataReceived == null) { return false; // We dont have a full match yet, we cannot work with missing values: skip this message } object[] compressedContents = data[(byte)2] as object[]; if (compressedContents == null) { // despite expectation, there is no compressed data in this msg. shouldn't happen. just a null check return false; } int[] indexesThatAreChangedToNull = data[(byte)3] as int[]; if (indexesThatAreChangedToNull == null) { indexesThatAreChangedToNull = new int[0]; } object[] lastReceivedData = view.lastOnSerializeDataReceived; for (int index = 0; index < compressedContents.Length; index++) { if (compressedContents[index] == null && !indexesThatAreChangedToNull.Contains(index)) { // we replace null values in this received msg unless a index is in the "changed to null" list object lastValue = lastReceivedData[index]; compressedContents[index] = lastValue; } } data[(byte)1] = compressedContents; // compressedContents are now uncompressed... return true; }
/// <summary> /// Compares the new data with previously sent data and skips values that didn't change. /// </summary> /// <returns>True if anything has to be sent, false if nothing new or no data</returns> private bool DeltaCompressionWrite(PhotonView view, Hashtable data) { if (view.lastOnSerializeDataSent == null) { return true; // all has to be sent } // We can compress as we sent a full update previously (readers can re-use previous values) object[] lastData = view.lastOnSerializeDataSent; object[] currentContent = data[(byte)1] as object[]; if (currentContent == null) { // no data to be sent return false; } if (lastData.Length != currentContent.Length) { // if new data isn't same length as before, we send the complete data-set uncompressed return true; } object[] compressedContent = new object[currentContent.Length]; int compressedValues = 0; List<int> valuesThatAreChangedToNull = new List<int>(); for (int index = 0; index < compressedContent.Length; index++) { object newObj = currentContent[index]; object oldObj = lastData[index]; if (this.ObjectIsSameWithInprecision(newObj, oldObj)) { // compress (by using null, instead of value, which is same as before) compressedValues++; // compressedContent[index] is already null (initialized) } else { compressedContent[index] = currentContent[index]; // value changed, we don't replace it with null // new value is null (like a compressed value): we have to mark it so it STAYS null instead of being replaced with previous value if (newObj == null) { valuesThatAreChangedToNull.Add(index); } } } // Only send the list of compressed fields if we actually compressed 1 or more fields. if (compressedValues > 0) { data.Remove((byte)1); // remove the original data (we only send compressed data) if (compressedValues == currentContent.Length) { // all values are compressed to null, we have nothing to send return false; } data[(byte)2] = compressedContent; // current, compressted data is moved to key 2 to mark it as compressed if (valuesThatAreChangedToNull.Count > 0) { data[(byte)3] = valuesThatAreChangedToNull.ToArray(); // data that is actually null (not just cause we didn't want to send it) } } return true; // some data was compressed but we need to send something }
/// <summary> /// Reads updates created by OnSerializeWrite /// </summary> private void OnSerializeRead(Hashtable data, PhotonPlayer sender, int networkTime, short correctPrefix) { // read view ID from key (byte)0: a int-array (PUN 1.17++) int viewID = (int)data[(byte)0]; PhotonView view = this.GetPhotonView(viewID); if (view == null) { Debug.LogWarning("Received OnSerialization for view ID " + viewID + ". We have no such PhotonView! Ignored this if you're leaving a room. State: " + this.State); return; } if (view.prefix > 0 && correctPrefix != view.prefix) { Debug.LogError("Received OnSerialization for view ID " + viewID + " with prefix " + correctPrefix + ". Our prefix is " + view.prefix); return; } // SetReceiving filtering if (view.group != 0 && !this.allowedReceivingGroups.Contains(view.group)) { return; // Ignore group } if (view.synchronization == ViewSynchronization.ReliableDeltaCompressed) { if (!this.DeltaCompressionRead(view, data)) { // Skip this packet as we haven't got received complete-copy of this view yet. if (PhotonNetwork.logLevel >= PhotonLogLevel.Informational) Debug.Log("Skipping packet for " + view.name + " [" + view.viewID + "] as we haven't received a full packet for delta compression yet. This is OK if it happens for the first few frames after joining a game."); return; } // store last received for delta-compression usage view.lastOnSerializeDataReceived = data[(byte)1] as object[]; } if (sender.ID != view.ownerId) { if (!view.isSceneView || !sender.isMasterClient) { // obviously the owner changed and we didn't yet notice. Debug.Log("Adjusting owner to sender of updates. From: " + view.ownerId + " to: " + sender.ID); view.ownerId = sender.ID; } } object[] contents = data[(byte)1] as object[]; PhotonStream pStream = new PhotonStream(false, contents); PhotonMessageInfo info = new PhotonMessageInfo(sender, networkTime, view); view.DeserializeView( pStream, info ); }
/// <summary> /// Sets properties of a player / actor. /// Internally this uses OpSetProperties, which can be used to either set room or player properties. /// </summary> /// <param name="actorNr">The payer ID (a.k.a. actorNumber) of the player to attach these properties to.</param> /// <param name="actorProperties">The properties to add or update.</param> /// <param name="expectedProperties">If set, these must be in the current properties-set (on the server) to set actorProperties: CAS.</param> /// <param name="webForward">Set to true, to forward the set properties to a WebHook, defined for this app (in Dashboard).</param> /// <returns>If the operation could be sent (requires connection).</returns> protected internal bool OpSetPropertiesOfActor(int actorNr, Hashtable actorProperties, Hashtable expectedProperties = null, bool webForward = false) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfActor()"); } if (actorNr <= 0 || actorProperties == null) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfActor not sent. ActorNr must be > 0 and actorProperties != null."); } return false; } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); opParameters.Add(ParameterCode.Properties, actorProperties); opParameters.Add(ParameterCode.ActorNr, actorNr); opParameters.Add(ParameterCode.Broadcast, true); if (expectedProperties != null && expectedProperties.Count != 0) { opParameters.Add(ParameterCode.ExpectedValues, expectedProperties); } if (webForward) { opParameters[ParameterCode.EventForward] = true; } //UnityEngine.Debug.Log(opParameters.ToStringFull()); return this.OpCustom((byte)OperationCode.SetProperties, opParameters, true, 0, false); }
private Hashtable GetLocalActorProperties() { if (PhotonNetwork.player != null) { return PhotonNetwork.player.allProperties; } Hashtable actorProperties = new Hashtable(); actorProperties[ActorProperties.PlayerName] = this.PlayerName; return actorProperties; }
/// <summary> /// Sets properties of a room. /// Internally this uses OpSetProperties, which can be used to either set room or player properties. /// </summary> /// <param name="gameProperties">The properties to add or update.</param> /// <param name="expectedProperties">The properties expected when update occurs. (CAS : "Check And Swap")</param> /// <param name="webForward">"WebFlag" to indicate if request should be forwarded as "PathProperties" webhook or not.</param> /// <returns>If the operation could be sent (has to be connected).</returns> protected internal bool OpSetPropertiesOfRoom(Hashtable gameProperties, Hashtable expectedProperties = null, bool webForward = false) { if (this.DebugOut >= DebugLevel.INFO) { this.Listener.DebugReturn(DebugLevel.INFO, "OpSetPropertiesOfRoom()"); } Dictionary<byte, object> opParameters = new Dictionary<byte, object>(); opParameters.Add(ParameterCode.Properties, gameProperties); opParameters.Add(ParameterCode.Broadcast, true); if (expectedProperties != null && expectedProperties.Count != 0) { opParameters.Add(ParameterCode.ExpectedValues, expectedProperties); } if (webForward) { opParameters[ParameterCode.EventForward] = true; } return this.OpCustom((byte)OperationCode.SetProperties, opParameters, true, 0, false); }
/// <summary>NetworkingPeer.OpJoinRandomRoom</summary> /// <remarks>this override just makes sure we have a mRoomToGetInto, even if it's blank (the properties provided in this method are filters. they are not set when we join the game)</remarks> public override bool OpJoinRandomRoom(Hashtable expectedCustomRoomProperties, byte expectedMaxPlayers, Hashtable playerProperties, MatchmakingMode matchingType, TypedLobby typedLobby, string sqlLobbyFilter) { this.mRoomToGetInto = new Room(null, null); this.mRoomToEnterLobby = null; // join random never stores the lobby. the following join will not affect the room lobby // if typedLobby is null, the server will automatically use the active lobby or default, which is what we want anyways this.mLastJoinType = JoinType.JoinRandomGame; return base.OpJoinRandomRoom(expectedCustomRoomProperties, expectedMaxPlayers, playerProperties, matchingType, typedLobby, sqlLobbyFilter); }
private void RoomOptionsToOpParameters(Dictionary<byte, object> op, RoomOptions roomOptions) { if (roomOptions == null) { roomOptions = new RoomOptions(); } Hashtable gameProperties = new Hashtable(); gameProperties[GamePropertyKey.IsOpen] = roomOptions.isOpen; gameProperties[GamePropertyKey.IsVisible] = roomOptions.isVisible; gameProperties[GamePropertyKey.PropsListedInLobby] = (roomOptions.customRoomPropertiesForLobby == null) ? new string[0] : roomOptions.customRoomPropertiesForLobby; gameProperties.MergeStringKeys(roomOptions.customRoomProperties); if (roomOptions.maxPlayers > 0) { gameProperties[GamePropertyKey.MaxPlayers] = roomOptions.maxPlayers; } op[ParameterCode.GameProperties] = gameProperties; op[ParameterCode.CleanupCacheOnLeave] = roomOptions.cleanupCacheOnLeave; // this is actually setting the room's config if (roomOptions.cleanupCacheOnLeave) { gameProperties[GamePropertyKey.CleanupCacheOnLeave] = true; // this is only informational for the clients which join } if (roomOptions.PlayerTtl > 0 || roomOptions.PlayerTtl == -1) { op[ParameterCode.CheckUserOnJoin] = true; // this affects rejoining a room. requires a userId to be used. added in v1.67 op[ParameterCode.PlayerTTL] = roomOptions.PlayerTtl; // TURNBASED op[ParameterCode.EmptyRoomTTL] = roomOptions.PlayerTtl; } //if (roomOptions.EmptyRoomTtl > 0) //{ // op[ParameterCode.EmptyRoomTTL] = roomOptions.EmptyRoomTtl; //TURNBASED //} if (roomOptions.suppressRoomEvents) { op[ParameterCode.SuppressRoomEvents] = true; } if (roomOptions.plugins != null) { op[ParameterCode.Plugins] = roomOptions.plugins; } if (roomOptions.publishUserId) { op[ParameterCode.PublishUserId] = true; } }
/// RPC Hashtable Structure /// (byte)0 -> (int) ViewId (combined from actorNr and actor-unique-id) /// (byte)1 -> (short) prefix (level) /// (byte)2 -> (int) server timestamp /// (byte)3 -> (string) methodname /// (byte)4 -> (object[]) parameters /// (byte)5 -> (byte) method shortcut (alternative to name) /// /// This is sent as event (code: 200) which will contain a sender (origin of this RPC). internal void RPC(PhotonView view, string methodName, PhotonTargets target, params object[] parameters) { if (this.blockSendingGroups.Contains(view.group)) { return; // Block sending on this group } if (view.viewID < 1) { Debug.LogError("Illegal view ID:" + view.viewID + " method: " + methodName + " GO:" + view.gameObject.name); } if (PhotonNetwork.logLevel >= PhotonLogLevel.Full) Debug.Log("Sending RPC \"" + methodName + "\" to " + target); //ts: changed RPCs to a one-level hashtable as described in internal.txt Hashtable rpcEvent = new Hashtable(); rpcEvent[(byte)0] = (int)view.viewID; // LIMITS NETWORKVIEWS&PLAYERS if (view.prefix > 0) { rpcEvent[(byte)1] = (short)view.prefix; } rpcEvent[(byte)2] = this.ServerTimeInMilliSeconds; // send name or shortcut (if available) int shortcut = 0; if (rpcShortcuts.TryGetValue(methodName, out shortcut)) { rpcEvent[(byte)5] = (byte)shortcut; // LIMITS RPC COUNT } else { rpcEvent[(byte)3] = methodName; } if (parameters != null && parameters.Length > 0) { rpcEvent[(byte)4] = (object[])parameters; } // Check scoping if (target == PhotonTargets.All) { RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group }; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); //this.OpRaiseEvent(PunEvent.RPC, (byte)view.group, rpcEvent, true, 0); // Execute local this.ExecuteRPC(rpcEvent, this.mLocalActor); } else if (target == PhotonTargets.Others) { RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group }; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); } else if (target == PhotonTargets.AllBuffered) { RaiseEventOptions options = new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache}; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); // Execute local this.ExecuteRPC(rpcEvent, this.mLocalActor); } else if (target == PhotonTargets.OthersBuffered) { RaiseEventOptions options = new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache }; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); } else if (target == PhotonTargets.MasterClient) { if (this.mMasterClient == this.mLocalActor) { this.ExecuteRPC(rpcEvent, this.mLocalActor); } else { RaiseEventOptions options = new RaiseEventOptions() { Receivers = ReceiverGroup.MasterClient }; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); } } else if (target == PhotonTargets.AllViaServer) { RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group, Receivers = ReceiverGroup.All }; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); if (PhotonNetwork.offlineMode) { this.ExecuteRPC(rpcEvent, this.mLocalActor); } } else if (target == PhotonTargets.AllBufferedViaServer) { RaiseEventOptions options = new RaiseEventOptions() { InterestGroup = (byte)view.group, Receivers = ReceiverGroup.All, CachingOption = EventCaching.AddToRoomCache }; this.OpRaiseEvent(PunEvent.RPC, rpcEvent, true, options); if (PhotonNetwork.offlineMode) { this.ExecuteRPC(rpcEvent, this.mLocalActor); } } else { Debug.LogError("Unsupported target enum: " + target); } }