private void SetPlayerScore() { string missionScoreName = "score" + missionName; if (PlayFabClientAPI.IsClientLoggedIn()) { if (PF_PlayerData.Statistics.ContainsKey(missionName)) { score.text = GetYourScoreText(PF_PlayerData.Statistics[missionName]); } if (PF_PlayerData.RankPositions.ContainsKey(missionName)) { rank.text = "Rank: " + (PF_PlayerData.RankPositions[missionName] + 1); } } else if (PlayerPrefs.HasKey(missionScoreName)) { score.text = GetYourScoreText(PlayerPrefs.GetInt(missionScoreName)); } }
/// <summary> /// PlayFab からランキングデータを取得する。 /// </summary> /// <returns></returns> public static async UniTask SyncPlayFabToClientAsync() { var request = new GetLeaderboardRequest { StatisticName = "Level", ProfileConstraints = new PlayerProfileViewConstraints { ShowDisplayName = true, ShowStatistics = true } }; var response = await PlayFabClientAPI.GetLeaderboardAsync(request); if (response.Error != null) { throw new PlayFabErrorException(response.Error); } UserLevelRanking = response.Result.Leaderboard.Select(x => RankingUser.CreateFromPlayerLeaderboardEntry(x)).ToArray(); }
void AddTradeToGroup(string tradeId) { Debug.Log(tradeId); ExecuteCloudScriptRequest executeRequest = new ExecuteCloudScriptRequest { FunctionName = "AddNewTradeOffer", FunctionParameter = new { tradeID = tradeId } }; PlayFabClientAPI.ExecuteCloudScript(executeRequest, result => { Trade.instance.SetDisplayText("Trade Offer Created", false); if (Trade.instance.onRefreshUI != null) { Trade.instance.onRefreshUI.Invoke(); } }, error => Trade.instance.SetDisplayText(error.ErrorMessage, true) ); }
public void LeaderBoard() { var clientRequest = new GetLeaderboardRequest(); clientRequest.MaxResultsCount = 3; clientRequest.StatisticName = TEST_STAT_NAME; PlayFabClientAPI.GetLeaderboard(clientRequest, GetClientLbCallback, SharedErrorCallback); WaitForApiCalls(); UUnitAssert.StringEquals("Get Client Leaderboard Successful", lastReceivedMessage); // Testing anything more would be testing actual functionality of the Leaderboard, which is outside the scope of this test. var serverRequest = new ServerModels.GetLeaderboardRequest(); serverRequest.MaxResultsCount = 3; serverRequest.StatisticName = TEST_STAT_NAME; PlayFabServerAPI.GetLeaderboard(serverRequest, GetServerLbCallback, SharedErrorCallback); WaitForApiCalls(); UUnitAssert.StringEquals("Get Server Leaderboard Successful", lastReceivedMessage); }
private static void OnFacebookLoggedIn(ILoginResult result) { if (result == null || (string.IsNullOrEmpty(result.Error) && !result.Cancelled)) { FB.API("/me?fields=name", HttpMethod.GET, (fbAccountInfo) => { if (fbAccountInfo.ResultDictionary.ContainsKey("name")) { displayName = (string)fbAccountInfo.ResultDictionary["name"]; PlayFabClientAPI.LoginWithFacebook(new LoginWithFacebookRequest { CreateAccount = true, AccessToken = AccessToken.CurrentAccessToken.TokenString }, OnPlayFabAuthSucess, OnPlayFabAuthFailed); } }); } else { Debug.Log("Error FB Login in: " + result.Error); OnFailed?.Invoke(); } }
public void Start() { GetPlayersLogin(); //Setting the title ID so playfab knows what endpoint to connect to just incase something buggs in editor if (string.IsNullOrEmpty(PlayFabSettings.TitleId)) { PlayFabSettings.TitleId = "F5079"; } //Check if user got credentials saved if (PlayerPrefs.HasKey("EMAIL")) { email = PlayerPrefs.GetString("EMAIL"); password = PlayerPrefs.GetString("PASSWORD"); var request = new LoginWithEmailAddressRequest { Email = email, Password = password }; PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnLoginFail); } }
void Start() { Debug.Log("Starting Auto-login Process"); #if PLAYFAB_IOS PlayFabClientAPI.LoginWithIOSDeviceID(new LoginWithIOSDeviceIDRequest { DeviceId = SystemInfo.deviceUniqueIdentifier, OS = SystemInfo.operatingSystem, DeviceModel = SystemInfo.deviceModel, CreateAccount = true }, onLoginSuccess, null); #elif PLAYFAB_ANDROID PlayFabClientAPI.LoginWithAndroidDeviceID(new LoginWithAndroidDeviceIDRequest { AndroidDeviceId = SystemInfo.deviceUniqueIdentifier, OS = SystemInfo.operatingSystem, AndroidDevice = SystemInfo.deviceModel, CreateAccount = true }, onLoginSuccess, null); #endif }
/// <summary> /// Calls the UpdateUserTitleDisplayName request API /// </summary> public static void UpdateDisplayName(string displayName, UnityAction <UpdateUserTitleDisplayNameResult> callback = null) { if (displayName.Length < 3 || 20 < displayName.Length) { return; } DialogCanvasController.RequestLoadingPrompt(PlayFabAPIMethods.UpdateDisplayName); var request = new UpdateUserTitleDisplayNameRequest { DisplayName = displayName }; PlayFabClientAPI.UpdateUserTitleDisplayName(request, result => { PF_Bridge.RaiseCallbackSuccess(string.Empty, PlayFabAPIMethods.UpdateDisplayName, MessageDisplayStyle.none); if (callback != null) { callback(result); } }, PF_Bridge.PlayFabErrorCallback); }
void SetUserData() { UpdateUserDataRequest request = new UpdateUserDataRequest() { Data = new Dictionary <string, string>() { { "name", input.text }, { "win", "0" }, { "lose", "0" } } }; PlayFabClientAPI.UpdateUserData(request, (result) => { Debug.Log("Successfully updated user data"); }, (error) => { Debug.Log("Got error setting user data Ancestor to Arthur"); Debug.Log(error.ErrorDetails); }); }
public void GetLeaderboardScore() { PlayFabClientAPI.ExecuteCloudScript( new ExecuteCloudScriptRequest() { FunctionName = "getPlayerStat", }, result => { if (result != null && result.FunctionResult != null) { LeaderBoardData data = JsonUtility.FromJson <LeaderBoardData>(result.FunctionResult.ToString()); score = data.pokemon_amount; } }, error => { Debug.Log("Error getting leaderboard"); } ); }
public static void OpenTrade(params string[] offeredInventoryInstanceIds) { var openRequest = new ClientModels.OpenTradeRequest(); // Optional field: null is anybody, alternately if specified, this is a targeted trade request // In this example, we restrict the trade to ourselves (because I don't have multiple clients for this example) // A normal trade process would use all the same steps, but would interact between multliple clients openRequest.AllowedPlayerIds = new List <string>() { PfSharedModelEx.globalClientUser.playFabId }; // Offering the items you have openRequest.OfferedInventoryInstanceIds = new List <string>(); openRequest.OfferedInventoryInstanceIds.AddRange(offeredInventoryInstanceIds); // Listing the items you want openRequest.RequestedCatalogItemIds = new List <string>() { PfSharedModelEx.swillItemId }; PlayFabClientAPI.OpenTrade(openRequest, OpenTradeCallback, PfSharedControllerEx.FailCallback("OpenTrade")); }
public void OnPlayFabSuccessLogin() { Client.PlayerName = DisplayName; RefreshNetInfo("正在对接 Photon..."); GetPhotonAuthenticationTokenRequest request = new GetPhotonAuthenticationTokenRequest(); request.PhotonApplicationId = AppId; PlayFabClientAPI.GetPhotonAuthenticationToken(request, res => { if (WaitPhotonStateDisposable != null) { WaitPhotonStateDisposable.Dispose(); } ConnectToMasterServer(PlayFabId, res.PhotonCustomAuthenticationToken); }, err => { Client.State = ClientState.Uninitialized; RefreshNetInfo("错误:无法从 PlayFab 获取 Photon Token"); }); }
public static Promise UpdateStatistic(Statistic statistic) { var promise = new Promise(); var request = new UpdatePlayerStatisticsRequest(); request.Statistics = new List <StatisticUpdate>() { new StatisticUpdate { StatisticName = statistic.type.ToString(), Value = statistic.bestValue } }; PlayFabClientAPI.UpdatePlayerStatistics(request, (result) => { try { UpdateStatisticSuccessCallback(result); promise.Resolve(); } catch (Exception ex) { promise.Reject(ex); } }, ErrorCallback); return(promise); }
public void LoadLeaderboard() { PlayFabClientAPI.GetLeaderboard( new GetLeaderboardRequest { StatisticName = STATISTIC_NAME, StartPosition = 0, MaxResultsCount = 10, }, result => { SetCurrentTime(); Debug.Log($"{result.Leaderboard.Count} players"); foreach (var item in result.Leaderboard.Select((v, i) => new { v, i })) { AddScore(item.i + 1, item.v.DisplayName, item.v.StatValue); } }, error => { Debug.LogError(error.GenerateErrorReport()); } ); }
void SendStatisticUpdate(int value) { var statisticUpdates = new List <StatisticUpdate> { new StatisticUpdate { StatisticName = STATISTIC_NAME, Value = value, } }; PlayFabClientAPI.UpdatePlayerStatistics( new UpdatePlayerStatisticsRequest { Statistics = statisticUpdates, }, result => { Debug.Log("Send score was succeeded"); }, error => { Debug.LogError(error.GenerateErrorReport()); } ); }
public void CreateAccount() { if (Password.text == ConfPassword.text) { RegisterPlayFabUserRequest request = new RegisterPlayFabUserRequest(); request.Username = Username.text; request.Password = ConfPassword.text; request.Email = Email.text; request.DisplayName = Username.text; PlayFabClientAPI.RegisterPlayFabUser(request, result => { Alerts a = new Alerts(); StartCoroutine(a.CreateNewAlert("Your Account " + result.Username + " Has been created!")); }, error => { Alerts a = new Alerts(); StartCoroutine(a.CreateNewAlert(error.ErrorMessage)); }); } }
public void LoginButton() { Player = new User(); string email = LoginEmailInput.text; string password = LoginPasswordInput.text; if (email == "" || password == "") { State = 3; ErrorMessageGenerator("Cannot leave field empty"); } else { Player = new User(email, password); var request = new LoginWithEmailAddressRequest { Email = Player.Email, Password = Player.Password }; PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnLoginFailure); } }
public void getFriendImageUrl(string id, Image image, GameObject imobject) { GetUserDataRequest getdatarequest = new GetUserDataRequest() { PlayFabId = id, }; PlayFabClientAPI.GetUserData(getdatarequest, (result) => { Dictionary <string, UserDataRecord> data = result.Data; imobject.SetActive(true); if (data.ContainsKey("PlayerAvatarUrl")) { // image.GetComponent<MonoBehaviour>().StartCoroutine(loadImage(data["PlayerAvatarUrl"].Value, image)); filterInputField.GetComponent <MonoBehaviour>().StartCoroutine(loadImage(data["PlayerAvatarUrl"].Value, image)); } }, (error) => { Debug.Log("Data updated error " + error.ErrorMessage); }, null); }
/// <summary> /// Login with PlayFab username. /// </summary> /// <param name="user">Username to use</param> /// <param name="pass">Password to use</param> public static void LoginWithUsername(string user, string password) { if (user.Length > 0 && password.Length > 0) { var request = new LoginWithPlayFabRequest { Username = user, Password = password, TitleId = PlayFabSettings.TitleId }; PlayFabClientAPI.LoginWithPlayFab(request, OnLoginResult, OnLoginError); } else { if (OnLoginFail != null) { OnLoginFail("User Name and Password cannot be blank.", MessageDisplayStyle.error); } } }
void Connect() { if (string.IsNullOrEmpty(PlayFabSettings.TitleId)) { PlayFabSettings.TitleId = "5555"; // Please change this value to your own titleId from PlayFab Game Manager } #if UNITY_ANDROID var requestAndroid = new LoginWithAndroidDeviceIDRequest { AndroidDeviceId = ReturnMobileID(), CreateAccount = true }; PlayFabClientAPI.LoginWithAndroidDeviceID(requestAndroid, OnLoginMobileSuccess, OnLoginMobileFailure); #endif #if UNITY_IOS var requestIOS = new LoginWithIOSDeviceIDRequest { DeviceId = ReturnMobileID(), CreateAccount = true }; PlayFabClientAPI.LoginWithIOSDeviceID(requestIOS, OnLoginMobileSuccess, OnLoginMobileFailure); #endif }
//玩家昵称设置成功时调用 void OnUpdateUserTitleDisplayName(UpdateUserTitleDisplayNameResult result) { /* 学生作业 2-3:玩家创建账号成功时,为玩家添加默认枪支:AK47 * 作业提示: * 先使用PurchaseItemRequest声明一个道具购买请求,再使用PlayFabClientAPI.PurchaseItem发起道具购买请求 * 道具购买成功,禁用游戏登录面板,启用游戏主面板(OnPurchaseItemRequest函数) * 道具购买失败,在控制台输出失败原因(OnPlayFabError函数) */ PurchaseItemRequest request = new PurchaseItemRequest() { CatalogVersion = PlayFabUserData.catalogVersion, VirtualCurrency = "FR", Price = 0, ItemId = "AK47" }; PlayFabClientAPI.PurchaseItem(request, OnPurchaseItemResult, OnPlayFabError); loginPanel.SetActive(false); //禁用游戏登录面板 mainPanel.SetActive(true); //启用游戏主面板 }
/// <summary> /// リーダーボードの取得 /// </summary> /// <param name="rankingName">ランキング名</param> /// <param name="startPosition">何位以降のランキングを取得するか</param> /// <param name="maxResultsCount">何件ランキングを取得するか</param> private void GetLeaderboard(string rankingName, int startPosition, int maxResultsCount) { // 通信待ちでなかったら通信開始 if (!waitConnect.GetWait(gameObject.name)) { // 通信待ちに設定する waitConnect.AddWait(gameObject.name); // GetLeaderboardRequestのインスタンスを生成 var request = new GetLeaderboardRequest { StatisticName = rankingName, //ランキング名(統計情報名) StartPosition = startPosition, //何位以降のランキングを取得するか MaxResultsCount = maxResultsCount //ランキングデータを何件取得するか(最大100) }; //ランキング(リーダーボード)を取得 Debug.Log($"ランキング(リーダーボード)の取得開始"); PlayFabClientAPI.GetLeaderboard(request, OnGetLeaderboardSuccess, OnGetLeaderboardFailure); } }
public static void UpdateUserStatistics(Dictionary <string, int> updates) { var request = new UpdatePlayerStatisticsRequest(); request.Statistics = new List <StatisticUpdate>(); foreach (var eachUpdate in updates) // Copy the stats from the inputs to the request { int eachStat; userStatistics.TryGetValue(eachUpdate.Key, out eachStat); request.Statistics.Add(new StatisticUpdate { StatisticName = eachUpdate.Key, Value = eachUpdate.Value }); // Send the value to the server userStatistics[eachUpdate.Key] = eachStat + eachUpdate.Value; // Update the local cache so that future updates are using correct values } print("points: "); print(LevelGoal.points); print("wins: "); print(LevelGoal.wins); PlayFabClientAPI.UpdatePlayerStatistics(request, OnUpdateUserStatisticsSuccess, OnUpdateUserStatisticsError); }
void Start() { dataManager = DataManager.dataManager; deckManager = DeckManager.deckManager; PlayerPrefs.DeleteAll(); if (string.IsNullOrEmpty(PlayFabSettings.TitleId)) { PlayFabSettings.TitleId = "7B285"; } if (PlayerPrefs.HasKey("EMAIL")) { userEmail = PlayerPrefs.GetString("EMAIL"); userPassword = PlayerPrefs.GetString("PASSWORD"); var request = new LoginWithEmailAddressRequest { Email = dataManager.GetEmail(), Password = dataManager.GetPassword() }; PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnLoginFailure); } }
private void UpdateStatistics() { UpdatePlayerStatisticsRequest statisticsRequest = new UpdatePlayerStatisticsRequest { Statistics = new List <StatisticUpdate>() { new StatisticUpdate { StatisticName = "HighScore", Value = this.CurrentNormalSoulsAmount } } }; PlayFabClientAPI.UpdatePlayerStatistics(statisticsRequest, null, OnUpdateFailed); void OnUpdateFailed(PlayFabError error) { Debug.Log(error.GenerateErrorReport()); } }
public static void UpdateInventory(Action callBack = null) { //取餘額 PlayFabClientAPI.GetUserInventory(new GetUserInventoryRequest(), userInventoryResult => { Inventory = userInventoryResult.Inventory; if (userInventoryResult.VirtualCurrency.TryGetValue("PI", out int _myMoney)) { PlayerManage.Wallet = _myMoney; } else { ModalHelper.WarningMessage("Not found PI Currency."); } callBack?.Invoke(); }, (errResult) => { ModalHelper.WarningMessage("Get VirtualCurrency fail."); }); }
private void SetUpPushNotification() { if (PlayFabClientAPI.IsClientLoggedIn() && !string.IsNullOrEmpty(PlayfabConstants.Instance.MyPlayfabID)) { if (string.IsNullOrEmpty(GameInvitationReceiver.Instance.FirebaseToken) || string.IsNullOrEmpty(PlayfabConstants.Instance.MyPlayfabID)) { return; } #if UNITY_ANDROID var request = new AndroidDevicePushNotificationRegistrationRequest { DeviceToken = GameInvitationReceiver.Instance.FirebaseToken, SendPushNotificationConfirmation = true, ConfirmationMessage = "Push notifications registered successfully" }; PlayFabClientAPI.AndroidDevicePushNotificationRegistration(request, OnPfAndroidReg => { Debug.Log("PUSH NOTIFICATION SET UP SUCCEDED"); }, OnPfFail => { Debug.Log("PUSH NOTIFICATION SET UP FAILED :" + OnPfFail.ErrorMessage); }); #endif } }
public void OnRegister() { RegisterPlayFabUserRequest registerRequest = new RegisterPlayFabUserRequest { Username = usernameInput.text, DisplayName = usernameInput.text, Password = passwordInput.text, RequireBothUsernameAndEmail = false }; PlayFabClientAPI.RegisterPlayFabUser(registerRequest, result => { SetDisplayText(result.PlayFabId, Color.green); }, error => { SetDisplayText(error.ErrorMessage, Color.red); } ); }
public void InvalidRegistration() { var registerRequest = new RegisterPlayFabUserRequest(); registerRequest.TitleId = PlayFabSettings.TitleId; registerRequest.Username = "******"; registerRequest.Email = "x"; registerRequest.Password = "******"; var registerTask = PlayFabClientAPI.RegisterPlayFabUserAsync(registerRequest); UUnitAssert.NotNull(registerTask.Result); UUnitAssert.IsNull(registerTask.Result.Result); UUnitAssert.NotNull(registerTask.Result.Error); var expectedEmailMsg = "email address is not valid."; var expectedPasswordMsg = "password must be between"; var fullReport = CompileErrorReport(registerTask.Result.Error); UUnitAssert.True(fullReport.ToLower().Contains(expectedEmailMsg), "Expected an error about bad email address: " + fullReport); UUnitAssert.True(fullReport.ToLower().Contains(expectedPasswordMsg), "Expected an error about bad password: " + fullReport); }
public void GetNews(Callback <List <IBasicNewsData> > successCallback) { StartRequest("Getting news"); GetTitleNewsRequest request = new GetTitleNewsRequest(); PlayFabClientAPI.GetTitleNews(request, (result) => { RequestComplete("GetNews complete", LogTypes.Info); List <IBasicNewsData> newsList = new List <IBasicNewsData>(); foreach (TitleNewsItem newsItem in result.News) { BasicNewsData news = JsonConvert.DeserializeObject <BasicNewsData>(newsItem.Body); news.Timestamp = newsItem.Timestamp; newsList.Add(news); } successCallback(newsList); }, (error) => { HandleError(error, BackendMessages.GET_NEWS_FAIL); }); }