# #c# #firebase #unity3d #firebase-realtime-database
Вопрос:
Я не могу читать из базы данных. Я могу подтвердить подлинность и сохранить. Просто не умею читать.
Я пробовал ContOnMainThread. Я попытался запустить функцию загрузки только после пения.
Я не могу найти ничего конкретного в этой ситуации.
Logcat(Сообщения, которыми я чувствовал, что должен поделиться)
2021/07/28 18:57:49.110 21378 25794 Warn Unity Player UID: sEtDwM1AGIVKMxR1fsJjwuPfrm32
2021/07/28 18:57:49.110 21378 25794 Warn Unity DatabaseSaveLoad:GetUID()
2021/07/28 18:57:49.110 21378 25794 Warn Unity DatabaseSaveLoad:Load()
2021/07/28 18:57:49.110 21378 25794 Warn Unity
2021/07/28 18:57:49.110 21378 25794 Warn Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.110 21378 25794 Warn Unity
2021/07/28 18:57:49.128 21378 25794 Info Unity Loading Complete
2021/07/28 18:57:49.128 21378 25794 Info Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.128 21378 25794 Info Unity
2021/07/28 18:57:49.136 21378 25794 Debug CompatibilityChangeReporter Compat change id reported: 147600208; UID 10844; state: ENABLED
2021/07/28 18:57:49.142 21378 25794 Warn Unity Config Built
2021/07/28 18:57:49.142 21378 25794 Warn Unity FirebaseManager:Start()
2021/07/28 18:57:49.142 21378 25794 Warn Unity
2021/07/28 18:57:49.142 21378 25794 Warn Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.142 21378 25794 Warn Unity
2021/07/28 18:57:49.142 21378 25794 Warn Unity Instance
2021/07/28 18:57:49.142 21378 25794 Warn Unity FirebaseManager:Start()
2021/07/28 18:57:49.142 21378 25794 Warn Unity
2021/07/28 18:57:49.142 21378 25794 Warn Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.142 21378 25794 Warn Unity
2021/07/28 18:57:49.142 21378 25794 Warn Unity Activate
2021/07/28 18:57:49.142 21378 25794 Warn Unity FirebaseManager:Start()
2021/07/28 18:57:49.142 21378 25794 Warn Unity
2021/07/28 18:57:49.142 21378 25794 Warn Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.142 21378 25794 Warn Unity
2021/07/28 18:57:49.143 21378 25794 Info Unity Starting Auth with token client.
2021/07/28 18:57:49.143 21378 25794 Info Unity GooglePlayGames.Android.AndroidClient:Authenticate(Boolean, Action`1)
2021/07/28 18:57:49.143 21378 25794 Info Unity FirebaseManager:Start()
2021/07/28 18:57:49.143 21378 25794 Info Unity
2021/07/28 18:57:49.143 21378 25794 Info Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.143 21378 25794 Info Unity
2021/07/28 18:57:49.144 21378 21378 Info SurfaceControl release : mNativeObject = 508408118416 - Surface(name=com.DefaultCompany.ProjectMeat/com.unity3d.player.UnityPlayerActivity$_21378)/@0x9404277 / android.view.SurfaceControl.assignNativeObject:567 android.view.SurfaceControl.readFromParcel:1115 android.view.IWindowSession$Stub$Proxy.relayout:1777 android.view.ViewRootImpl.relayoutWindow:8953
2021/07/28 18:57:49.144 21378 21378 Info SurfaceControl nativeRelease nativeObject s[508408118416]
2021/07/28 18:57:49.144 21378 21378 Info SurfaceControl nativeRelease nativeObject e[508408118416]
2021/07/28 18:57:49.145 21378 21378 Info SurfaceControl assignNativeObject: nativeObject = 0 Surface(name=null)/@0x15f1dab / android.view.SurfaceControl.readFromParcel:1115 android.view.IWindowSession$Stub$Proxy.relayout:1787 android.view.ViewRootImpl.relayoutWindow:8953 android.view.ViewRootImpl.performTraversals:3312 android.view.ViewRootImpl.doTraversal:2575 android.view.ViewRootImpl$TraversalRunnable.run:9916 android.view.Choreographer$CallbackRecord.run:1010 android.view.Choreographer.doCallbacks:809 android.view.Choreographer.doFrame:744 android.view.Choreographer$FrameDisplayEventReceiver.run:995
2021/07/28 18:57:49.145 21378 25794 Warn Unity Player UID: sEtDwM1AGIVKMxR1fsJjwuPfrm32
2021/07/28 18:57:49.145 21378 25794 Warn Unity DatabaseSaveLoad:GetUID()
2021/07/28 18:57:49.145 21378 25794 Warn Unity DatabaseSaveLoad:Start()
2021/07/28 18:57:49.145 21378 25794 Warn Unity
2021/07/28 18:57:49.145 21378 25794 Warn Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.145 21378 25794 Warn Unity
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl release : mNativeObject = 508408389280 - Surface(name=Surface(name=ac99350 InputMethod)/@0xdc80f6f - animation-leash)/@0x3ab2a49 / android.view.-$Lambda$Rl1VZmNJ0VZDLK0BAbaVGis0rrA.accept:2 android.view.InsetsSourceControl.release:170 android.view.InsetsSourceConsumer.setControl:202 android.view.ImeInsetsSourceConsumer.setControl:154
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl nativeRelease nativeObject s[508408389280]
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl nativeRelease nativeObject e[508408389280]
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl release : mNativeObject = 508408141296 - Surface(name=Surface(name=ba0644c NavigationBar0)/@0xfef046e - animation-leash)/@0x4396f4e / android.view.-$Lambda$Rl1VZmNJ0VZDLK0BAbaVGis0rrA.accept:2 android.view.InsetsSourceControl.release:170 android.view.InsetsSourceConsumer.setControl:202 android.view.InsetsController.onControlsChanged:833
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl nativeRelease nativeObject s[508408141296]
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl nativeRelease nativeObject e[508408141296]
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl release : mNativeObject = 508408136016 - Surface(name=Surface(name=3472d89 StatusBar)/@0xe6c8822 - animation-leash)/@0x7bba97c / android.view.-$Lambda$Rl1VZmNJ0VZDLK0BAbaVGis0rrA.accept:2 android.view.InsetsSourceControl.release:170 android.view.InsetsSourceConsumer.setControl:202 android.view.InsetsController.onControlsChanged:833
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl nativeRelease nativeObject s[508408136016]
2021/07/28 18:57:49.146 21378 21378 Info SurfaceControl nativeRelease nativeObject e[508408136016]
2021/07/28 18:57:49.146 21378 21378 Info ViewRootImpl@a3a4625[UnityPlayerActivity] Relayout returned: old=(0,74,1080,2400) new=(0,74,1080,2400) req=(1080,2326)0 dur=5 res=0x1 s={true 512702957648} ch=false fn=7
2021/07/28 18:57:49.146 21378 21378 Info ViewRootImpl@a3a4625[UnityPlayerActivity] updateBoundsLayer: shouldReparent = false t = android.view.SurfaceControl$Transaction@65d8a02 sc = Surface(name=Bounds for - com.DefaultCompany.ProjectMeat/com.unity3d.player.UnityPlayerActivity@0)/@0x56c8f13 frame = 7
2021/07/28 18:57:49.149 21378 25794 Debug HelperFragment Creating fragment
2021/07/28 18:57:49.151 21378 21378 Debug HelperFragment onResume called
2021/07/28 18:57:49.151 21378 21378 Debug SignInRequest signIn
2021/07/28 18:57:49.151 21378 21378 Debug SignInRequest Building client for: 8fdac14 (a:true e:false i:false wc: 605567159672-fennfincvvsj4vp07u1ufd4imksmhs73.apps.googleusercontent.com f: false)
2021/07/28 18:57:49.151 21378 21378 Debug SignInRequest canReuseAccount: false
2021/07/28 18:57:49.151 21378 21378 Debug SignInRequest signInClient.silentSignIn
2021/07/28 18:57:49.257 21378 25970 Info UnityAds com.unity3d.services.core.configuration.InitializeThread$InitializeStateLoadCache.execute() (line:253) :: Unity Ads init: webapp loaded from local cache
2021/07/28 18:57:49.270 21378 21378 Info WebViewFactory Loading com.google.android.webview version 92.0.4515.115 (code 451511534)
2021/07/28 18:57:49.285 21378 21378 Info cr_WVCFactoryProvider Loaded version=92.0.4515.115 minSdkVersion=29 isBundle=true multiprocess=true packageId=2
2021/07/28 18:57:49.293 21378 21378 Info cr_LibraryLoader Successfully loaded native library
2021/07/28 18:57:49.294 21378 21378 Info cr_CachingUmaRecorder Flushed 8 samples from 8 histograms.
2021/07/28 18:57:49.295 21378 21378 Info TetheringManager registerTetheringEventCallback:com.DefaultCompany.ProjectMeat
2021/07/28 18:57:49.296 21378 21378 Debug ConnectivityManager ConnectivityManager() mContext=android.app.Application@2524c69 getOpPackageName()=com.DefaultCompany.ProjectMeat getBasePackageName()=com.DefaultCompany.ProjectMeat getPackageName()=com.DefaultCompany.ProjectMeat
2021/07/28 18:57:49.397 21378 26025 Warn cr_media Requires BLUETOOTH permission
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 QUALCOMM build : 0e5772e1da, I227baa4eae
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Build Date : 02/16/21
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 OpenGL ES Shader Compiler Version: EV031.32.02.08
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Local Branch :
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Remote Branch :
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Remote Branch :
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Reconstruct Branch :
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Build Config : S P 10.0.7 AArch64
2021/07/28 18:57:49.408 21378 26050 Info AdrenoGLES-0 Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021/07/28 18:57:49.411 21378 26050 Info AdrenoGLES-0 PFP: 0x016dd091, ME: 0x00000000
2021/07/28 18:57:49.683 21378 26075 Info UnityAds com.unity3d.services.core.api.Sdk.logInfo() (line:82) :: mediation detection is:{"UnityEngine":true}
2021/07/28 18:57:49.694 21378 25986 Warn SyncTree Listen at /users failed: DatabaseError: Permission denied
2021/07/28 18:57:49.701 21378 26075 Info UnityAds com.unity3d.services.core.api.Sdk.logInfo() (line:82) :: Requesting configuration from https://publisher-config.unityads.unity3d.com/games/4175169/configuration?deviceMake=samsungamp;screenDensity=420amp;screenSize=268435810amp;idfi=62b8b3bf-ec0f-434b-836a-d6d308a9cd43amp;advertisingTrackingId=2d6b53db-7fc1-4e3e-93c4-1e8002722969amp;limitAdTracking=falseamp;connectionType=wifiamp;screenHeight=2287amp;screenWidth=1080amp;bundleId=com.DefaultCompany.ProjectMeatamp;encrypted=trueamp;rooted=falseamp;platform=androidamp;sdkVersion=3480amp;osVersion=11amp;deviceModel=SM-G988Uamp;language=en_USamp;test=falseamp;analyticsUserId=48e2e9927da877673a52c684999e0798amp;analyticsSessionId=3407644339022458612amp;first=falseamp;framework=[object Object]amp;adapter=[object Object]
2021/07/28 18:57:49.703 21378 26093 Info System.out (HTTPLog)-Static: isSBSettingEnabled false
2021/07/28 18:57:49.703 21378 26093 Info System.out (HTTPLog)-Static: isSBSettingEnabled false
2021/07/28 18:57:49.703 21378 25794 Error Unity Error: Firebase
2021/07/28 18:57:49.703 21378 25794 Error Unity System.Action`1:Invoke(T)
2021/07/28 18:57:49.703 21378 25794 Error Unity Firebase.Extensions.<ContinueWithOnMainThread>c__AnonStorey9:<>m__0()
2021/07/28 18:57:49.703 21378 25794 Error Unity System.Func`1:Invoke()
2021/07/28 18:57:49.703 21378 25794 Error Unity Firebase.<RunAsync>c__AnonStorey1`1:<>m__0()
2021/07/28 18:57:49.703 21378 25794 Error Unity System.Action:Invoke()
2021/07/28 18:57:49.703 21378 25794 Error Unity Firebase.ExceptionAggregator:Wrap(Action)
2021/07/28 18:57:49.703 21378 25794 Error Unity Firebase.Dispatcher:PollJobs()
2021/07/28 18:57:49.703 21378 25794 Error Unity Firebase.Platform.FirebaseHandler:Update()
2021/07/28 18:57:49.703 21378 25794 Error Unity
2021/07/28 18:57:49.703 21378 25794 Error Unity (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
2021/07/28 18:57:49.703 21378 25794 Error Unity
Это мой сценарий FirebaseManager/аутентификации
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading.Tasks;
using Firebase;
using Firebase.Auth;
using Firebase.Database;
public class FirebaseManager : MonoBehaviour
{
public DatabaseSaveLoad databaseSaveLoad;
private void Start()
{
// Initialize Play Games Configuration and Activate it.
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.RequestServerAuthCode(false)
.Build();
Debug.LogWarning("Config Built");
PlayGamesPlatform.InitializeInstance(config); Debug.LogWarning("Instance");
PlayGamesPlatform.Activate(); Debug.LogWarning("Activate");
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance; // Sign In and Get a server auth code.
UnityEngine.Social.localUser.Authenticate((bool success) =>
{
if (!success)
{
Debug.LogError("SignInOnClick: Failed to Sign into Play Games Services.");
return;
}
string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
if (string.IsNullOrEmpty(authCode))
{
Debug.LogError("SignInOnClick: Signed into Play Games Services but failed to get the server auth code.");
return;
}
Debug.LogFormat("SignInOnClick: Auth code is: {0}", authCode); // Use Server Auth Code to make a credential
Firebase.Auth.Credential credential = Firebase.Auth.PlayGamesAuthProvider.GetCredential(authCode); // Sign In to Firebase with the credential
auth.SignInWithCredentialAsync(credential).ContinueWith(task => {
if (task.IsCanceled)
{
Debug.LogError("SignInOnClick was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInOnClick encountered an error: " task.Exception);
return;
}
Firebase.Auth.FirebaseUser newUser = task.Resu<
Debug.LogWarning("SignInOnClick: User signed in successfully");
});
});
}
}
This is my «DatabaseSave/Load» Sctipt
using Firebase.Database;
using Firebase.Extensions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DatabaseSaveLoad : MonoBehaviour
{
[Header("Script References")]
public MasterManager MM;
[Header("Save System")]
public bool IsLoading;
public WaitForSeconds AutoSaveInterval = new WaitForSeconds(10);
[Header("User Information")]
public string UID;
[Header("Firebase")]
public DatabaseReference reference;
// Start //
void Start()
{
reference = FirebaseDatabase.DefaultInstance.RootReference;
GetUID();
StartCoroutine(StartLoad());
AutoSave();
}
// Pause //
public void OnApplicationPause(bool pause)
{
if (pause == true)
{
Save();
}
else
{
Load();
}
}
// Coroutines //
public void AutoSave()
{
StartTheCoroutine = TheCoroutine();
StartCoroutine(StartTheCoroutine);
}
private IEnumerator StartTheCoroutine;
public IEnumerator TheCoroutine()
{
while (true)
{
yield return AutoSaveInterval;
Save();
}
}
// Load
public IEnumerator StartLoad()
{
yield return new WaitForSeconds(1);
Load();
}
// Save //
public void Save()
{
if (!IsLoading)
{
//GetUID();// Check for players UID.
PlayerSaveData saveData = new PlayerSaveData();
Debug.LogWarning("Sending to Database");
// Player Data Entered Below This Comment //
// Money //
saveData.MoneyOHAmount = MM.MoneyOH;
// Player Data END //
string json = JsonUtility.ToJson(saveData); // Convert to JSON
reference.Child("users").Child(UID).SetRawJsonValueAsync(json); // Send to Firebase Database as JSON
Debug.LogWarning("Sent complete");
}
}
// Load //
public void Load()
{
IsLoading = true;
Debug.Log("Loading1");
GetUID();
PlayerSaveData saveData = new PlayerSaveData(); // New instance of PlayerSaveData.cs
FirebaseDatabase.DefaultInstance.GetReference("users").OrderByChild(UID).GetValueAsync().ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Error: Firebase");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Resu<
string json = snapshot.Child(UID).GetRawJsonValue();
saveData = JsonUtility.FromJson<PlayerSaveData>(json);
// Load Data //
// LOAD DATA BELOW THIS LINE //
// Money //
MM.MoneyOH = saveData.MoneyOHAmount;
// LOAD DATA END //
}
});
IsLoading = false;
Debug.Log("Loading Complete");
}
// Get USER ID //
public void GetUID()
{
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null)
{
string playerName = user.DisplayName;
string uid = user.UserId;
Debug.LogWarning("Player UID: " uid);
UID = uid;
}
else
{
UID = "No UID";
}
}
}
My Firebase rules are as follows
{
"rules": {
"users": {
"$uid": {
// Allow only authenticated content owners access to their data
".read": "auth != null",
".write": "auth.uid == $uid"
}
}
}
}
[Правка] Добавить Скрипт базы данных.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class PlayerSaveData
{
[Header("Money")]
public double MoneyOHAmount;
public double MoneyThisRunAmount;
public double MoneyAllTimeAmount;
public double MoneySpentThisRunAmount;
public double MoneySpentAllTimeAmount;
public double MoneyBeforeBoostsAmount;
public double MoneyAfterBoostAmount;
[Header("Premium")]
public double CloudCoinsOHAmount;
public double CloudCoinsThisRunAmount;
public double CloudCoinsAllTimeAmount;
[Header("Player Boosts")]
// Consumables
public bool X2For5MinutesActiveBool;
public bool Discount25PerCentBool;
public bool xBoost25PerCentXPBool;
// Upgrades
public float RacksPerDayCCUpgradeLVLAmount;
[Header("Time")]
public int SecondsAmount;
public int MinutesAmount;
public int HoursAmount;
public int DaysAmount;
public bool IsPMBool;
public bool TimeSkipBool;
[Header("Player: Stats")]
public string PlayerUIDString;
public float PlayerClothingLevelAmount;
public float HatRankAmount;
public float ShirtRankAmount;
public float PantsRankAmount;
public float ShoesRankAmount;
public float HireChanceAmount;
public float SleepAmountAmount;
public float TimesUsedBenchTodayAmount;
[Header("Currently Equipped")]
public bool HasLameHatBool;
public bool HasCoolHatBool;
public bool HasRadHatBool;
[Space]
public bool HasLameShirtBool;
public bool HasCoolShirtBool;
public bool HasRadShirtBool;
[Space]
public bool HasLamePantsBool;
public bool HasCoolPantsBool;
public bool HasRadPantsBool;
[Space]
public bool HasLameShoesBool;
public bool HasCoolShoesBool;
public bool HasRadShoesBool;
[Space]
public bool HasHat1Bool;
public bool HasHat2Bool;
public bool HasHat3Bool;
[Space]
public bool HasShirt1Bool;
public bool HasShirt2Bool;
public bool HasShirt3Bool;
[Space]
public bool HasPants1Bool;
public bool HasPants2Bool;
public bool HasPants3Bool;
[Space]
public bool HasShoes1Bool;
public bool HasShoes2Bool;
public bool HasShoes3Bool;
// PA //
public bool NotAPrinterBool;
[Header("Tutorials")]
// Tut: Shop7
public bool Shop7TutorialReadBool;
public bool Shop7WorkTutorialReadBool;
public bool Shop7InvestmentTutorialReadBool;
// Tut: Thrift Store
public bool ThriftStoreItemPanelReadBool;
public bool ThriftStoreStatPanelReadBool;
public bool ThriftStoreShopButtonReadBool;
public bool ThriftStoreRackReadBool;
// Tut: Hotel
public bool HotelCostReadBool;
// Tut: General
public bool ClothingRankTutorialReadBool;
[Header("Clothing Stats")]
public double CurrentHatSpeedStatAmount;
public double CurrentHatIncomeStatAmount;
public double CurrentHatSaleStatAmount;
//
public double CurrentShirtSpeedStatAmount;
public double CurrentShirtIncomeStatAmount;
public double CurrentShirtSaleStatAmount;
//
public double CurrentPantsSpeedStatAmount;
public double CurrentPantsIncomeStatAmount;
public double CurrentPantsSaleStatAmount;
//
public double CurrentShoesSpeedStatAmount;
public double CurrentShoesIncomeStatAmount;
public double CurrentShoesSaleStatAmount;
// Shops //
[Header("Shop7")]
public int CoffeeOHAmount;
public int CoffeeInStockAmount;
public int StarberryOHAmount;
public int StarberryInStockAmount;
public int OctoPopOHAmount;
public int OctoPopInStockAmount;
public bool Shop7OpenBool;
[Header("Thrift Store")]
public int RackStockAmount;
public bool HasShoppedHatsTodayTSBool;
public bool HasShoppedShirtsTodayTSBool;
public bool HasShoppedPantsTodayTSBool;
public bool HasShoppedShoesTodayTSBool;
public bool ThriftStoreOpenBool;
// Work //
[Header("Shop7 Work")]
public double Shop7WorkLevelAmount;
public double Shop7WorkCurrentXPAmount;
public bool HasAJobAtShop7Bool;
public bool HasInterviewedTodayShop7Bool;
[Header("Thrift Stoe Work")]
public double ThriftStoreWorkLevelAmount;
public double ThriftStoreWorkCurrentXPAmount;
public bool HasAJobAtThriftStoreBool;
public bool ThriftStoreCanWorkBool;
public bool HasInterviewedTodayThriftStoreBool;
// Investing //
[Header("Shop7 Investing")]
public double Shop7AmountInvestedAmount;
public double Shop7InvestedLevelAmount;
public double Shop7ROIPercentageAmount;
public double Shop7CapitalGainsAmount;
[Header("ThriftStore Investing")]
public double ThriftStoreAmountInvestedAmount;
public double ThriftStoreInvestedLevelAmount;
public double ThriftStoreROIPercentageAmount;
public double ThriftStoreCapitalGainsAmount;
// Map Idle Business' //
[Header("Map Idle Business'")]
// M1P1
public double M1P1InvestedAmount;
public double M1P1MinCPHLvlAmount;
public double M1P1MaxCPHLvlAmount;
public double M1P1SellValueLvlAmount;
public float M1P1CPHMinAmount;
public float M1P1CPHMaxAmount;
public bool M1P1CompleteBool;
// M1P2
public double M1P2InvestedAmount;
public double M1P2MinCPHLvlAmount;
public double M1P2MaxCPHLvlAmount;
public double M1P2SellValueLvlAmount;
public float M1P2CPHMinAmount;
public float M1P2CPHMaxAmount;
public bool M1P2CompleteBool;
// Trash //
[Header("Shop7 Trash")]
public bool Shop7TrashAvailableBool;
public int TimesLookedInShop7TrashAmount;
public int TimeLookedInShop7TrashAmount;
}
Я могу аутентифицироваться и сохранять в сборке Google Play.
Я пробовал разные варианты запуска load() void.
Я надеюсь, что предоставил вам достаточно информации, чтобы вы могли мне помочь! Я ценю, что вы не торопитесь.
Спасибо!
Комментарии:
1. Какова структура вашей базы данных? Может быть, вы пытаетесь получить доступ к значению, которого не существует?
2. И как вы можете войти
Debug.LogWarning("Sent complete");
в систему, если вы даже не знаете, правда ли это? Вы просто знаете, что началиSetRawJsonValueAsync
бит, никогда не проверяйте, действительно ли это удалось, и если да, то вы не ждете, а сразу же просто предполагаете, что это сработало.3. Я пытаюсь узнать все это, поэтому я пришел сюда, чтобы задать несколько вопросов. Я изо всех сил стараюсь освоить этот новый шаг. Я понятия не имел об этом типе структуры кода, пока не начал заниматься firebase. Я занимаюсь исключительно единством с начала прошлого года. Я положил туда этот журнал, чтобы знать, что функция сработала. Я наблюдал за своей базой, чтобы узнать, отправляются ли данные, что и есть. Я просто не могу прочитать данные.
4. Один из способов обхода, который я нашел, состоит в том, чтобы установить правила базы данных firebase так, чтобы
{ "rules": { "users": { ".read": "auth.uid !== null", ".write": "auth.uid !== null" } } }
я предпочел, чтобы они были установлены так, чтобы пользователь мог изменять только свои собственные. Может быть, это недопустимо при том, как я настроил свою систему на стороне unity?
Ответ №1:
Ваши правила должны быть такими:
{
"rules": {
"users": {
"$uid": {
".read": "$uid !== null",
".write": "$uid === auth.uid"
}
}
}
}
С веб-консоли firebase вы можете использовать игровую площадку для проверки своих правил. Очень полезно для настройки правил базы данных.
PS 1) В настоящее время вы читаете информацию для всех пользователей и на стороне клиента получаете данные для текущего пользователя. Это не будет масштабироваться. Вместо этого вы могли читать данные только для текущего пользователя:
FirebaseDatabase.DefaultInstance.GetReference($"users/{UID}").GetValueAsync().ContinueWithOnMainThread(t => ...);
PS 2) В качестве примечания, когда вы получаете исключение, рекомендуется просмотреть его сообщение. В Firebase обычно есть полезные сообщения об исключениях. Firebase обычно объединяет свои исключения, поэтому должно быть сделано что-то вроде приведенного ниже:
if (task.IsFaulted)
{
Debug.LogError($"Firebase Error: {task.Exception.Flatten().InnerException.Message}");
}
Комментарии:
1. « База данных на основе огня. Установка по умолчанию. getReference($»пользователи/{UID}»). GetValueAsync().ContinueWithOnMainThread(t => …); ` Ты потрясающий!!!