CharacterSelection.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using Firebase.Extensions;
  4. using Firebase.Firestore;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. public class CharacterSelection : MonoBehaviour
  8. {
  9. [SerializeField] public static string selectedCharJson = "";
  10. public List<CharacterDataSO> predefinedCharacterJsons;
  11. public List<Button> predefinedCharacterButtons;
  12. public static Action OnCharacterChanged;
  13. void Start()
  14. {
  15. for (int i = 0; i < predefinedCharacterButtons.Count; i++)
  16. {
  17. int tempI = i;
  18. predefinedCharacterButtons[i].onClick.AddListener(() => { OnPredefinedCharButtonPress(tempI); });
  19. }
  20. LoadCharacterSkinCloud();
  21. }
  22. public void LoadCharacterFromString(string characterData)
  23. {
  24. selectedCharJson = characterData;
  25. OnCharacterChanged?.Invoke();
  26. }
  27. void OnPredefinedCharButtonPress(int i)
  28. {
  29. selectedCharJson = predefinedCharacterJsons[i].jsonCharData;
  30. OnCharacterChanged?.Invoke();
  31. SaveCharacterSkinCloud();
  32. }
  33. public static void SaveCharacterSkinCloud()
  34. {
  35. #if UNITY_EDITOR
  36. PlayerPrefs.SetString("skinData", selectedCharJson);
  37. PlayerPrefs.Save();
  38. #else
  39. FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
  40. Dictionary<string,object> skindataDictionary = new Dictionary<string, object>();
  41. skindataDictionary.Add("json", selectedCharJson);
  42. DocumentReference docRef = db.Collection("SkinData").Document(gplayAuth.userID);
  43. docRef.SetAsync(skindataDictionary).ContinueWithOnMainThread(task => {
  44. if(task.IsCompleted){
  45. Debug.Log("**** Save Completed Firestore ****");
  46. }
  47. else{
  48. Debug.Log("**** Failed to save data to firestore ****");
  49. }
  50. });
  51. #endif
  52. }
  53. void LoadCharacterSkinCloud()
  54. {
  55. #if UNITY_EDITOR
  56. if (PlayerPrefs.HasKey("skinData"))
  57. {
  58. LoadCharacterFromString(PlayerPrefs.GetString("skinData"));
  59. }
  60. #else
  61. FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
  62. DocumentReference docRef = db.Collection("SkinData").Document(gplayAuth.userID);
  63. docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
  64. DocumentSnapshot snapshot = task.Result;
  65. if(snapshot.Exists){
  66. LoadCharacterFromString(snapshot.GetValue<string>("json"));
  67. }else{
  68. //show error previous data doesnt exists to load
  69. Debug.Log("**** No previous data to load ****");
  70. }
  71. });
  72. #endif
  73. }
  74. }