// Use this for initialization void Start() { // damageRadius = 50; // damage = 20; // range = 500; v0 = 200; string name = gameObject.name.Split('(')[0]; Debug.Log(gameObject.name); foreach (CatalogItem i in GameInfo.catalogItems) { //Debug.Log (i.ItemId.Split('-')[0]); // 把临时道具的时间信息去掉,比如'-1day' if (i.ItemId.Split('-')[0] == name) { Dictionary <string, string> data = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> > (i.CustomData); string rangeStr, damageStr, radiusStr; data.TryGetValue("炮弹射程", out rangeStr); data.TryGetValue("炮弹威力", out damageStr); data.TryGetValue("爆炸范围", out radiusStr); range = float.Parse(rangeStr); damage = int.Parse(damageStr); damageRadius = float.Parse(radiusStr); break; } } Debug.Log("炮弹射程" + range + " 炮弹威力" + damage + " 爆炸范围" + damageRadius + "。"); }
/// <summary> /// Creates a new <c>FunctionTaskContext</c> out of the incoming request to an Azure Function. /// </summary> /// <param name="request">The request incoming to an Azure Function from the PlayFab server</param> /// <returns>A new populated <c>FunctionTaskContext</c> instance</returns> public static async Task <FunctionTaskContext <TFunctionArgument> > Create(HttpRequestMessage request) { using (var content = request.Content) { var body = await content.ReadAsStringAsync(); var contextInternal = PlayFabSimpleJson.DeserializeObject <FunctionTaskContextInternal>(body); var settings = new PlayFabApiSettings { TitleId = contextInternal.TitleAuthenticationContext.Id, DeveloperSecretKey = Environment.GetEnvironmentVariable("PLAYFAB_DEV_SECRET_KEY", EnvironmentVariableTarget.Process) }; var authContext = new PlayFabAuthenticationContext { EntityToken = contextInternal.TitleAuthenticationContext.EntityToken }; return(new FunctionTaskContext <TFunctionArgument>() { ApiSettings = settings, AuthenticationContext = authContext, ScheduledTaskNameId = contextInternal.ScheduledTaskNameId, EventHistory = contextInternal.EventHistory, FunctionArgument = contextInternal.FunctionArgument }); } }
private static async Task <object> ExtractFunctionResult(HttpContent content) { string responseContent = await content.ReadAsStringAsync(); if (!string.IsNullOrWhiteSpace(responseContent)) { // JSON object or array if (responseContent.StartsWith("{") || responseContent.StartsWith("[")) { return(PlayFabSimpleJson.DeserializeObject(responseContent)); } // JSON number else if (float.TryParse(responseContent, out float f)) { return(f); } // JSON true or false else if (bool.TryParse(responseContent, out bool b)) { return(b); } else // JSON string { return(responseContent); } } return(null); }
public static async Task <dynamic> UnlockHighSkillContent( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, ILogger log) { /* Create the function execution's context through the request */ var context = await FunctionPlayerPlayStreamContext <dynamic> .Create(req); var args = context.FunctionArgument; var playerStatUpdatedEvent = PlayFabSimpleJson.DeserializeObject <dynamic>(context.PlayStreamEventEnvelope.EventData); var request = new UpdateUserInternalDataRequest { PlayFabId = context.CurrentPlayerId, Data = new Dictionary <string, string> { { "HighSkillContent", "true" }, { "XPAtHighSkillUnlock", playerStatUpdatedEvent["StatisticValue"].ToString() } } }; /* Use the ApiSettings and AuthenticationContext provided to the function as context for making API calls. */ var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext); /* Execute the Server API request */ var updateUserDataResponse = await serverApi.UpdateUserInternalDataAsync(request); log.LogInformation($"Unlocked HighSkillContent for {context.PlayerProfile.DisplayName}"); return(new { profile = context.PlayerProfile }); }
public EventSignal <T> Send <T>(IConnection connection, string data) { string _url = connection.Url + "send"; string _customQueryString = GetCustomQueryString(connection); _url += String.Format( c_sendQueryString, m_transport, Uri.EscapeDataString(connection.ConnectionToken), _customQueryString); var _postData = new Dictionary <string, string> { { "data", data }, }; var _returnSignal = new EventSignal <T>(); var _postSignal = m_httpClient.PostAsync(_url, connection.PrepareRequest, _postData); _postSignal.Finished += (sender, e) => { string _raw = e.Result.ReadAsString(); if (String.IsNullOrEmpty(_raw)) { _returnSignal.OnFinish(default(T)); return; } _returnSignal.OnFinish(PlayFabSimpleJson.DeserializeObject <T>(_raw)); }; return(_returnSignal); }
public static TestTitleData VerifyTestTitleData() { #if NET45 || NETCOREAPP2_0 if (TestTitleData == null) { try { var testTitleDataPath = Environment.GetEnvironmentVariable("PF_TEST_TITLE_DATA_JSON"); var jsonContent = File.ReadAllText(testTitleDataPath + "/testTitleData.json"); TestTitleData = PlayFabSimpleJson.DeserializeObject <TestTitleData>(jsonContent); } catch (Exception) { } } #endif // Fall back on hard coded testTitleData if necessary (Put your own data here) if (TestTitleData == null) { TestTitleData = new TestTitleData { titleId = "6195", userEmail = "*****@*****.**" } } ; PlayFabSettings.staticSettings.TitleId = TestTitleData.titleId; return(TestTitleData); }
public override IEnumerator ExecuteRequest() { var request = new ExecuteFunctionRequest { FunctionName = Constants.AI_MOVE_FUNCTION_NAME, FunctionParameter = new PlayFabIdRequest { PlayFabId = Player.PlayFabId }, AuthenticationContext = new PlayFabAuthenticationContext { EntityToken = Player.EntityToken } }; PlayFabCloudScriptAPI.ExecuteFunction(request, (result) => { ExecutionCompleted = true; AIMoveResult = PlayFabSimpleJson.DeserializeObject <TicTacToeMove>(result.FunctionResult.ToString()); }, (error) => { throw new Exception($"MakeAIMove request failed. Message: {error.ErrorMessage}, Code: {error.HttpCode}"); }); yield return(WaitForExecution()); }
//初始化 void Start() { playerHealth = GetComponent <PlayerHealth> (); //获取玩家PlayerHealth组件 myCamera = Camera.main; timer = 0.0f; //初始化玩家与上次射击的间隔 if (photonView.isMine) { //根据本地玩家的天赋等级技能,设置玩家的射击参数 Dictionary <string, string> gunData = null; foreach (CatalogItem i in GameInfo.catalogItems) { if (i.ItemClass == PlayFabUserData.equipedWeapon) { gunData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(i.CustomData); break; } } Dictionary <string, string> skillData = null; float value; int myShootingDamage = 0; float myShootingRange = 0.0f, myTimeBetweenShooting = 0.0f, myRecoilForce = 1.0f; foreach (KeyValuePair <string, string> kvp in gunData) { switch (kvp.Key) { //计算枪械威力 case "枪械威力": skillData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(GameInfo.titleData["ShootingDamageSkill"]); value = float.Parse(kvp.Value) * (1.0f + float.Parse(skillData["Level" + PlayFabUserData.shootingDamageSkillLV.ToString()]) / 100); myShootingDamage = (int)value; break; //计算枪械射程 case "枪械射程": skillData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(GameInfo.titleData["ShootingRangeSkill"]); value = float.Parse(kvp.Value) * (1.0f + float.Parse(skillData["Level" + PlayFabUserData.shootingRangeSkillLV.ToString()]) / 100); myShootingRange = value; break; //计算射击间隔 case "射击间隔": skillData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(GameInfo.titleData["ShootingIntervalSkill"]); value = float.Parse(kvp.Value) * (1.0f - float.Parse(skillData["Level" + PlayFabUserData.shootingIntervalSkillLV.ToString()]) / 100); myTimeBetweenShooting = value; break; //计算后坐力(暂时不影响玩家射击) case "后坐力": myRecoilForce = float.Parse(kvp.Value); break; } } //初始化其他节点中,该玩家的射击参数 photonView.RPC("Init", PhotonTargets.All, PlayFabUserData.equipedWeapon, myShootingDamage, myShootingRange, myTimeBetweenShooting, myRecoilForce); } }
public void TestDeserializeToObject(UUnitTestContext testContext) { var testInt = PlayFabSimpleJson.DeserializeObject <object>("1"); var testString = PlayFabSimpleJson.DeserializeObject <object>("\"a string\""); testContext.IntEquals((int)(ulong)testInt, 1); testContext.StringEquals((string)testString, "a string"); testContext.EndTest(UUnitFinishState.PASSED, null); }
private static T Convert <T>(object obj) { if (obj == null) { return(default(T)); } if (typeof(T).IsAssignableFrom(obj.GetType())) { return((T)obj); } return(PlayFabSimpleJson.DeserializeObject <T>(obj.ToString())); }
public static string GetApiVersion(ApiCategory apiCategory) { var packageJson = (TextAsset)AssetDatabase.LoadAssetAtPath(Path.Combine(Strings.Package.BuildPath(apiCategory), "package.json"), typeof(TextAsset)); if (packageJson != null) { return(PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(packageJson.text)["version"]); } else { return(null); } }
//显示成就奖励条目 void ShowRewardItems() { int length = rewardItems.Length, i; Dictionary <string, string> myData; Text[] texts; Button button; //显示成就奖励条目 for (i = 0; i < rewardKeys.Count; i++) { string rewardName = rewardKeys[i]; texts = rewardItems[i].GetComponentsInChildren <Text>(); button = rewardItems[i].GetComponentInChildren <Button>(); myData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(rewardData[rewardName]); int rewardValue = int.Parse(myData["RewardValue"]); //成就奖励 texts[1].text = myData["RewardValue"]; //累计获得成就点和奖励目标成就点 texts[2].text = "累计获得成就点" + PlayFabUserData.achievementPoints + "/" + myData["TargetPoints"]; //如果成就奖励已领取 if (PlayFabUserData.userData.ContainsKey(rewardName)) { button.interactable = false; texts[3].text = "已领取"; } //如果成就奖励未领取,且成就奖励目标已达成 else if (PlayFabUserData.achievementPoints >= int.Parse(myData["TargetPoints"])) { button.interactable = true; button.onClick.RemoveAllListeners(); button.onClick.AddListener(delegate() { GetReward(rewardName, rewardValue); }); texts[3].text = "领取"; } //如果成就奖励未完成 else { button.interactable = false; texts[3].text = "未完成"; } rewardItems[i].SetActive(true); } for (; i < length; i++) { rewardItems[i].SetActive(false); } }
//添加经验值 void AddUserExp(int resultWeight) { var playerCustomProperties = PhotonNetwork.player.customProperties; int expAmount = 20 + 50 * resultWeight + 10 * (int)playerCustomProperties["Score"] - 1 * (int)playerCustomProperties["Death"]; Dictionary <string, string> skillData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(GameInfo.titleData["ExpAndMoneySkill"]); expAmount = (int)((float)expAmount * (1.0f + float.Parse(skillData["Level" + PlayFabUserData.expAndMoneySkillLV.ToString()]) / 100)); GMInstance.UIController.showExpReward(expAmount); PlayFabUserData.exp += expAmount; if (PlayFabUserData.exp >= GameInfo.levelExps[PlayFabUserData.lv] && GameInfo.levelExps[PlayFabUserData.lv] != -1) { PlayFabUserData.exp -= GameInfo.levelExps[PlayFabUserData.lv]; PlayFabUserData.lv++; } }
private static string GetHostRoutePrefix() { string hostFileContent = null; string currDir = Directory.GetCurrentDirectory(); string currDirHostFile = Path.Combine(currDir, "host.json"); if (File.Exists(currDirHostFile)) { hostFileContent = ReadAllFileText(currDirHostFile); } var hostModel = PlayFabSimpleJson.DeserializeObject <HostJsonModel>(hostFileContent); return(hostModel?.extensions?.http?.routePrefix ?? _defaultRoutePrefix); }
/// <summary> /// Raises the retrive quest items success event. /// </summary> /// <param name="result">Result.</param> public static void OnRetriveQuestItemsSuccess(ExecuteCloudScriptResult result) { if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result)) { return; } Debug.Log(result.ToString()); QuestProgress.ItemsGranted = PlayFabSimpleJson.DeserializeObject <List <ItemGrantResult> >(result.FunctionResult.ToString()); PF_GamePlay.QuestProgress.areItemsAwarded = true; //PF_PlayerData.GetCharacterInventory(PF_PlayerData.activeCharacter.characterDetails.CharacterId); //PF_PlayerData.GetUserInventory(); PF_Bridge.RaiseCallbackSuccess("Items granted", PlayFabAPIMethods.RetriveQuestItems, MessageDisplayStyle.none); }
//添加金币 void AddUserCurrency(int resultWeight) { var playerCustomProperties = PhotonNetwork.player.customProperties; int currencyAmount = 20 + 200 * resultWeight + 10 * (int)playerCustomProperties["Score"] - 1 * (int)playerCustomProperties["Death"]; Dictionary <string, string> skillData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(GameInfo.titleData["ExpAndMoneySkill"]); currencyAmount = (int)((float)currencyAmount * (1.0f + float.Parse(skillData["Level" + PlayFabUserData.expAndMoneySkillLV.ToString()]) / 100)); GMInstance.UIController.showCurrencyReward(currencyAmount); AddUserVirtualCurrencyRequest request = new AddUserVirtualCurrencyRequest() { VirtualCurrency = "GC", Amount = currencyAmount }; PlayFabClientAPI.AddUserVirtualCurrency(request, (result) => { }, (error) => { }); }
public static void OnDrawCharactersSuccess(ExecuteCloudScriptResult result) { if (!PF_Bridge.VerifyErrorFreeCloudScriptResult(result)) { return; } if (result.FunctionResult.ToString() != "false") { List <string> grantedName = PlayFabSimpleJson.DeserializeObject <List <string> >(result.FunctionResult.ToString()); PF_Bridge.RaiseCallbackSuccess(grantedName[0], PlayFabAPIMethods.DrawCharacterToUser, MessageDisplayStyle.none); } else { PF_Bridge.RaiseCallbackSuccess("you dont have enough money to draw", PlayFabAPIMethods.DrawCharacterToUser, MessageDisplayStyle.none); } }
/// <summary> /// Fetch's an entity's profile from the PlayFab server /// </summary> /// <param name="callerEntityToken">The entity token of the entity profile being fetched</param> /// <returns>The entity's profile</returns> private static async Task <EntityProfileBody> GetEntityProfile(string callerEntityToken, EntityKey entity) { // Construct the PlayFabAPI URL for GetEntityProfile var getProfileUrl = GetServerApiUri("/Profile/GetProfile"); // Create the get entity profile request var profileRequest = new GetEntityProfileRequest { Entity = entity }; // Prepare the request headers var profileRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(profileRequest)); profileRequestContent.Headers.Add("X-EntityToken", callerEntityToken); profileRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); PlayFabJsonSuccess <GetEntityProfileResponse> getProfileResponseSuccess = null; GetEntityProfileResponse getProfileResponse = null; // Execute the get entity profile request using (var profileResponseMessage = await httpClient.PostAsync(getProfileUrl, profileRequestContent)) { using (var profileResponseContent = profileResponseMessage.Content) { string profileResponseString = await profileResponseContent.ReadAsStringAsync(); // Deserialize the http response getProfileResponseSuccess = PlayFabSimpleJson.DeserializeObject <PlayFabJsonSuccess <GetEntityProfileResponse> >(profileResponseString); // Extract the actual get profile response from the deserialized http response getProfileResponse = getProfileResponseSuccess?.data; } } // If response object was not filled it means there was an error if (getProfileResponseSuccess?.data == null || getProfileResponseSuccess?.code != 200) { throw new Exception($"Failed to get Entity Profile: code: {getProfileResponseSuccess?.code}"); } return(getProfileResponse.Profile); }
public static void OnGetTitleDataSuccess(GetTitleDataResult result) { Debug.Log("OnGetTitleDataSuccess"); Debug.Log("OnGetTitleDataSuccess -- Spells"); if (result.Data.ContainsKey("Spells")) { Spells = PlayFabSimpleJson.DeserializeObject <Dictionary <string, FG_SpellDetail> >(result.Data["Spells"]); Debug.Log(string.Format("{0} Spell count found", Spells.Count)); } Debug.Log("OnGetTitleDataSuccess -- Classes"); if (result.Data.ContainsKey("Classes")) { Classes = PlayFabSimpleJson.DeserializeObject <Dictionary <string, FG_ClassDetail> >(result.Data["Classes"]); Debug.Log(string.Format("{0} Classes count found", Classes.Count)); } Debug.Log("OnGetTitleDataSuccess -- Levels"); if (result.Data.ContainsKey("Levels")) { Levels = PlayFabSimpleJson.DeserializeObject <Dictionary <string, FG_LevelData> >(result.Data["Levels"]); Debug.Log(Levels.Count + " sbdaibdaiubdiabba"); } Debug.Log("OnGetTitleDataSuccess -- MinimumInterstitialWait"); if (result.Data.ContainsKey("MinimumInterstitialWait")) { MinimumInterstitialWait = float.Parse(result.Data["MinimumInterstitialWait"]); } Debug.Log("OnGetTitleDataSuccess -- CharacterLevelRamp"); if (result.Data.ContainsKey("CharacterLevelRamp")) { CharacterLevelRamp = PlayFabSimpleJson.DeserializeObject <Dictionary <string, int> >(result.Data["CharacterLevelRamp"]); } if (result.Data.ContainsKey("StandardStores")) { //StandardStores = PlayFabSimpleJson.DeserializeObject<List<string>>(result.Data["StandardStores"]); Debug.Log("Standard Stores Retrieved"); } PF_Bridge.RaiseCallbackSuccess("Title Data Loaded", PlayFabAPIMethods.GetTitleData, MessageDisplayStyle.none); }
protected override void OnReceived(JsonObject message) { var _invocation = PlayFabSimpleJson.DeserializeObject <HubInvocation>(message.ToString()); HubProxy _hubProxy; if (m_hubs.TryGetValue(_invocation.Hub, out _hubProxy)) { if (_invocation.State != null) { foreach (var state in _invocation.State) { _hubProxy[state.Key] = state.Value; } } _hubProxy.InvokeEvent(_invocation.Method, _invocation.Args); } base.OnReceived(message); }
internal static string GetLocalSettingsFileProperty(string propertyKey) { string envFileContent = null; string currDir = Directory.GetCurrentDirectory(); string currDirEnvFile = Path.Combine(currDir, _localSettingsFileName); if (File.Exists(currDirEnvFile)) { envFileContent = ReadAllFileText(currDirEnvFile); } else { string tempDir = Path.GetTempPath(); string tempDirEnvFile = Path.Combine(tempDir, _localSettingsFileName); if (File.Exists(tempDirEnvFile)) { envFileContent = ReadAllFileText(tempDirEnvFile); } } if (!string.IsNullOrEmpty(envFileContent)) { JsonObject envJson = PlayFabSimpleJson.DeserializeObject <JsonObject>(envFileContent); try { object result; if (envJson.TryGetValue(propertyKey, out result)) { return(result == null ? string.Empty : result.ToString()); } return(null); } catch (KeyNotFoundException) { return(string.Empty); } } return(string.Empty); }
void RetrieveCharacterData(ushort ConnectedClientID, string characterID) { PlayFab.DataModels.EntityKey characterEntityKey = CreateKeyForEntity(characterID, "character"); GetObjectsRequest getObjectsRequest = CreateGetCharacterObjectRequestEscaped(characterEntityKey); PlayFabDataAPI.GetObjects(getObjectsRequest, result => { PlayFabCharacterData characterData = PlayFabSimpleJson.DeserializeObject <PlayFabCharacterData>(result.Objects["CharacterData"].EscapedDataObject); Debug.Log($"character position for retrieved character: {characterData.WorldPositionX}, {characterData.WorldPositionY}, {characterData.WorldPositionZ}"); characterData.SetWorldPosition(characterData.WorldPositionX, characterData.WorldPositionY, characterData.WorldPositionZ); Debug.Log($"character position AS VECTOR 3 for retrieved character: {characterData.WorldPosition.ToString()}"); SetCurrentCharacterDataForConnectedClient(ConnectedClientID, characterData); }, error => { Debug.Log("Error setting player info from PlayFab result object"); Debug.Log(error.ErrorMessage); }); }
// 显示选中道具的详细信息 void OnEnable() { item = InventoryPanelController.userItems [InventoryPanelController.selectedItem]; itemName.text = item.DisplayName; // itemImage.sprite = GameInfo.guns [item.ItemClass]; //显示道具的图片 //显示道具的详细信息(PlayFab GameManager存储的道具自定义属性) foreach (CatalogItem i in GameInfo.catalogItems) { if (i.ItemId == item.ItemId) { customData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(i.CustomData); break; } } itemDescription.text = ""; string temp = ""; foreach (KeyValuePair <string, string> kvp in customData) { temp += "\n" + kvp.Key + ":" + kvp.Value; } itemDescription.text = temp.Substring(1); confirmButton.GetComponentInChildren <Text>().text = "装备"; confirmButton.interactable = true; // 动态绑定购买按钮的事件 confirmButton.onClick.RemoveAllListeners(); confirmButton.onClick.AddListener(delegate { confirmButton.GetComponentInChildren <Text>().text = "装备中"; confirmButton.interactable = false; PlayFabUserData.equipedWeapon = item.ItemId; Dictionary <string, string> data = new Dictionary <string, string>(); data.Add("EquipedWeapon", item.ItemId); UpdateUserDataRequest request = new UpdateUserDataRequest() { Data = data }; PlayFabClientAPI.UpdateUserData(request, OnUpdateUserData, OnPlayFabError); InventoryPanelController.isEquiped = true; gameObject.SetActive(false); }); }
internal static EventSignal <NegotiationResponse> GetNegotiationResponse( IHttpClient httpClient, IConnection connection) { string _negotiateUrl = connection.Url + "negotiate"; var _negotiateSignal = new EventSignal <NegotiationResponse>(); var _signal = httpClient.GetAsync(_negotiateUrl, connection.PrepareRequest); _signal.Finished += (sender, e) => { string _raw = e.Result.ReadAsString(); if (_raw == null) { throw new InvalidOperationException("Server negotiation failed."); } _negotiateSignal.OnFinish(PlayFabSimpleJson.DeserializeObject <NegotiationResponse>(_raw)); }; return(_negotiateSignal); }
//================================================================================= //JSON形式でのタイトルデータの取得処理 //================================================================================= public void GetTitleData() { PlayFabClientAPI.GetTitleData(new GetTitleDataRequest(), result => { if (result.Data.ContainsKey("CollectionData")) { // デシリアライズしてリストに変換 var CharaMasterData = PlayFabSimpleJson.DeserializeObject <List <CollectionData> >(result.Data["CollectionData"]); foreach (var chara in CharaMasterData) { var CharaData = new Dictionary <string, string>() { { "ID", chara.ID }, { "Name", chara.Name }, { "EnName", chara.EnName }, { "Time", chara.Time }, { "Category", chara.Category }, { "KeyWord", chara.KeyWord }, { "ImgTitle", chara.ImgTitle }, { "AvatorName", chara.AvatorName }, { "PanelText", chara.PanelText }, { "Location", chara.Location } }; CharaDataList.Add(CharaData); } } // 初回ログインでない場合は、CharaDataListの値がセットできてから、プレイヤーデータをplayFabから取得 if (_shouldCreateAccount == false) { GetUserData(); } }, error => { Debug.Log(error.GenerateErrorReport()); } ); }
// ユーザーデータを取得して、CharaDataListにユーザーデータをマージします。 void GetUserData() { Debug.Log("(2)GetUserData()が呼び出されました"); PlayFabClientAPI.GetUserData(new GetUserDataRequest(), result => { var SavedCharaInfos = PlayFabSimpleJson.DeserializeObject <List <SavedCharaInfo> >(result.Data["SavedCharaInfo"].Value); for (int i = 0; i < SavedCharaInfos.Count; i++) { // CharaDataListにユーザーデータから取得したStatusの値を追加 CharaDataList[i].Add("Status", SavedCharaInfos[i].Status); // PlayFabController.CharaDataList[i]["Name"]; } // Debug.Log("(3)2回目以降のログインの取得結果:" + CharaDataList[0]["Status"]); // Debug.Log("(3)2回目以降のログインの取得結果:" + CharaDataList[3]["Status"]); }, error => { Debug.Log("(2)プレイヤーデータの取得に失敗!!"); Debug.Log(error.GenerateErrorReport()); }); }
public static async Task <TicTacToeState> GetCurrentGameState(string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext) { var request = new GetUserDataRequest() { PlayFabId = playFabId, Keys = new List <string>() { Constants.GAME_CURRENT_STATE_KEY } }; var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext); var result = await serverApi.GetUserDataAsync(request); if (result.Error != null) { throw new Exception($"An error occurred while fetching the current game state: Error: {result.Error.GenerateErrorReport()}"); } var resultData = result.Result.Data; // Current state found if (resultData.Count > 0 && resultData.TryGetValue(Constants.GAME_CURRENT_STATE_KEY, out var currentGameStateRecord)) { return(PlayFabSimpleJson.DeserializeObject <TicTacToeState>(currentGameStateRecord.Value)); } // Current game record does not exist and so must be created else { var newState = new TicTacToeState() { Data = new int[9] }; await UpdateCurrentGameState(newState, playFabId, apiSettings, authenticationContext); return(newState); } }
// 显示选中道具的详细信息 void OnEnable() { item = ShopPanelController.shopItems [ShopPanelController.selectedItem]; itemName.text = item.DisplayName; if (item.VirtualCurrencyPrices.ContainsKey("JB")) { price.text = "金币:" + item.VirtualCurrencyPrices ["JB"].ToString(); } //显示道具的详细信息(PlayFab GameManager存储的道具自定义属性) customData = PlayFabSimpleJson.DeserializeObject <Dictionary <string, string> >(item.CustomData); itemDescription.text = ""; string temp = ""; foreach (KeyValuePair <string, string> kvp in customData) { temp += "\n" + kvp.Key + ":" + kvp.Value; } itemDescription.text = temp.Substring(1); confirmButton.GetComponentInChildren <Text>().text = "购买"; confirmButton.interactable = true; // 动态绑定购买按钮的事件 confirmButton.onClick.RemoveAllListeners(); confirmButton.onClick.AddListener(delegate { confirmButton.GetComponentInChildren <Text>().text = "购买中"; confirmButton.interactable = false; if (item.VirtualCurrencyPrices.ContainsKey("JB")) { PurchaseItemRequest request = new PurchaseItemRequest() { CatalogVersion = PlayFabUserData.catalogVersion, VirtualCurrency = "JB", Price = (int)item.VirtualCurrencyPrices ["JB"], ItemId = item.ItemId }; PlayFabClientAPI.PurchaseItem(request, OnPurchaseItem, OnPlayFabPurchaseError); } }); }
/// <summary> /// Grabs the developer secret key from the environment variable (expected to be set) and uses it to /// ask the PlayFab server for a title entity token. /// </summary> /// <returns>The title's entity token</returns> private static async Task <string> GetTitleEntityToken() { var titleEntityTokenRequest = new AuthenticationModels.GetEntityTokenRequest(); var getEntityTokenUrl = GetServerApiUri("/Authentication/GetEntityToken"); // Grab the developer secret key from the environment variables (app settings) to use as header for GetEntityToken var secretKey = Environment.GetEnvironmentVariable(DEV_SECRET_KEY, EnvironmentVariableTarget.Process); if (string.IsNullOrEmpty(secretKey)) { // Environment variable was not set on the app throw new Exception("Could not fetch the developer secret key from the environment. Please set \"PLAYFAB_DEV_SECRET_KEY\" in your app's local.settings.json file."); } var titleEntityTokenRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(titleEntityTokenRequest)); titleEntityTokenRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); titleEntityTokenRequestContent.Headers.Add("X-SecretKey", secretKey); using (var titleEntityTokenResponseMessage = await httpClient.PostAsync(getEntityTokenUrl, titleEntityTokenRequestContent)) { using (var titleEntityTokenResponseContent = titleEntityTokenResponseMessage.Content) { string titleEntityTokenResponseString = await titleEntityTokenResponseContent.ReadAsStringAsync(); // Deserialize the http response var titleEntityTokenResponseSuccess = PlayFabSimpleJson.DeserializeObject <PlayFabJsonSuccess <AuthenticationModels.GetEntityTokenResponse> >(titleEntityTokenResponseString); // Extract the actual get title entity token header var titleEntityTokenResponse = titleEntityTokenResponseSuccess.data; return(titleEntityTokenResponse.EntityToken); } } }
public static void GetCharacterDataById(string characterId) { DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.GetCharacterReadOnlyData); GetCharacterDataRequest request = new GetCharacterDataRequest(); //request.PlayFabId = PlayFabSettings.PlayerId; request.CharacterId = characterId; request.Keys = new List <string>() { "CharacterData" }; PlayFabClientAPI.GetCharacterReadOnlyData(request, (result) => { if (result.Data.ContainsKey("CharacterData")) { playerCharacterData[result.CharacterId] = PlayFabSimpleJson.DeserializeObject <FG_CharacterData>(result.Data["CharacterData"].Value); PF_Bridge.RaiseCallbackSuccess("", PlayFabAPIMethods.GetCharacterReadOnlyData, MessageDisplayStyle.none); } }, PF_Bridge.PlayFabErrorCallback); }