using UnityEngine; using PlayFab; using PlayFab.ClientModels; using System.Collections.Generic; public class PlayerPrefsSyncManager : MonoBehaviour { private static PlayerPrefsSyncManager instance; private void OnApplicationQuit() { SyncPlayerPrefsToPlayFabOnQuit(); } private void OnApplicationPause() { SyncPlayerPrefsToPlayFabOnQuit(); } private void OnApplicationFocus(bool focus) { //if (!focus) SyncPlayerPrefsToPlayFabOnQuit(); } void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(this.gameObject); Application.quitting += SyncPlayerPrefsToPlayFabOnQuit; } else { Destroy(gameObject); } } private const int MaxKeysPerRequest = 10; public void SyncPlayerPrefsToPlayFabOnQuit() { if (PlayFabClientAPI.IsClientLoggedIn()) { var keys = PlayerPrefsKeys.GetAllKeys(); if (keys.Count == 0) { Debug.Log("No PlayerPrefs keys registered, skipping sync."); return; } Dictionary allPrefs = new Dictionary(); foreach (var key in keys) { string strVal = PlayerPrefs.GetString(key, "__MISSING__"); if (strVal != "__MISSING__") { allPrefs[key] = "string:" + strVal; continue; } int intVal = PlayerPrefs.GetInt(key, int.MinValue + 1); if (intVal != int.MinValue + 1) { allPrefs[key] = "int:" + intVal; continue; } float floatVal = PlayerPrefs.GetFloat(key, float.MinValue + 1); if (floatVal != float.MinValue + 1) { allPrefs[key] = "float:" + floatVal.ToString("R"); } } foreach (var pair in allPrefs) { Debug.Log($"[Sync] {pair.Key} = {pair.Value}"); } // Split into batches of 10 var batches = new List>(); var currentBatch = new Dictionary(); foreach (var pair in allPrefs) { currentBatch[pair.Key] = pair.Value; if (currentBatch.Count == MaxKeysPerRequest) { batches.Add(currentBatch); currentBatch = new Dictionary(); } } if (currentBatch.Count > 0) { batches.Add(currentBatch); } UploadPlayerPrefsBatches(batches, 0); } } private void UploadPlayerPrefsBatches(List> batches, int index) { if (index >= batches.Count) { Debug.Log("✅ All PlayerPrefs batches synced to PlayFab."); return; } var request = new UpdateUserDataRequest { Data = batches[index], Permission = UserDataPermission.Public }; PlayFabClientAPI.UpdateUserData(request, result => { Debug.Log($"✅ Synced batch {index + 1}/{batches.Count}"); UploadPlayerPrefsBatches(batches, index + 1); }, error => { Debug.LogError($"❌ Failed to sync batch {index + 1}/{batches.Count}: {error.GenerateErrorReport()}"); }); } }