Unity C#使用Firebase时变量赋值执行顺序异常问题
Ah, I get it, this is a super common issue with asynchronous operations like Firebase's Database calls in Unity! Let me break down why your logs are out of order and how to get your logic running in the sequence you expect.
Why the Logs Are Out of Order
Firebase's database operations (like GetValueAsync()) run asynchronously. That means when you call it, Unity doesn't pause the main thread to wait for the database response — it fires off the request and immediately moves on to the next line of code (your Debug.Log("Outside: "+currentScore);).
By the time the database call finishes and updates currentScore, that outside log has already executed with the original value. That's exactly why you're seeing:
Outside: origData , Inside: origData , Inside Updated: firebaseResponse
How to Fix It
You need to ensure any code that depends on the Firebase database result runs after the asynchronous operation completes. Here are two clean, practical ways to do this:
1. Use ContinueWith with Main Thread Context
Wrap your post-database logic in a ContinueWith callback, and make sure it runs on Unity's main thread (critical if you plan to interact with UI or other Unity APIs later):
string currentScore = "origData"; var fbReference = FirebaseDatabase.DefaultInstance.GetReference("your/database/path"); fbReference.GetValueAsync().ContinueWith(task => { // Handle errors first if (task.IsFaulted) { Debug.LogError("Database request failed: " + task.Exception); return; } if (task.IsCompleted) { DataSnapshot snapshot = task.Result; currentScore = snapshot.Value.ToString(); // Your inner logs run first, as expected Debug.Log("Inside: " + currentScore); Debug.Log("Inside Updated: " + currentScore); // Now run your "outside" log AFTER the database operation finishes Debug.Log("Outside: " + currentScore); } }, TaskScheduler.FromCurrentSynchronizationContext()); // Ensures callback runs on Unity's main thread
2. Use async/await (Cleaner, More Readable)
If you're using Unity 2017.1 or later, async/await lets you write asynchronous code that looks almost like synchronous code — this is my go-to for readability:
using System.Threading.Tasks; // Mark the method as async (void works for one-off calls/event handlers) async void FetchScoreAndRunLogic() { string currentScore = "origData"; var fbReference = FirebaseDatabase.DefaultInstance.GetReference("your/database/path"); try { // Wait for the database call to complete before moving on DataSnapshot snapshot = await fbReference.GetValueAsync(); currentScore = snapshot.Value.ToString(); // All logs now run in the correct order Debug.Log("Inside: " + currentScore); Debug.Log("Inside Updated: " + currentScore); Debug.Log("Outside: " + currentScore); } catch (System.Exception e) { Debug.LogError("Database error: " + e.Message); } } // Call this method instead of your original code block FetchScoreAndRunLogic();
Key Takeaway
Asynchronous operations like Firebase calls don't block the main thread (great for keeping your game responsive!), but that means you can't rely on linear code execution for logic that depends on their results. Always wrap code that needs the database response inside the async callback or after an await statement.
内容的提问来源于stack exchange,提问作者drdrdrdrdr2

