You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Unity编辑器中Firebase匿名登录如何保留固定UserId?

Fixing Persistent Anonymous User ID in Firebase Unity Editor (SDK 4.5.0+)

Great question! I’ve dealt with this exact frustration when testing anonymous auth in the Unity editor—nothing breaks workflow more than getting a fresh user ID every time you restart the editor. Let’s break down how to fix this:

First, the core issue: On devices, Firebase automatically persists anonymous auth credentials to platform-specific storage (like Keychain on iOS or SharedPreferences on Android). But the Unity editor doesn’t have this built-in persistence, so SignInAnonymouslyAsync() generates a new user every session.

The Solution: Manually Persist the Refresh Token

We can use Unity’s PlayerPrefs (which persists across editor restarts) to save the anonymous user’s refresh token, then use that token to re-authenticate the same user when the editor launches again. Here’s a step-by-step implementation:

  1. Wrap editor-specific logic: Use #if UNITY_EDITOR to ensure this code only runs in the editor and doesn’t affect device builds.
  2. Check for saved credentials: On startup, look for a stored refresh token in PlayerPrefs.
  3. Re-authenticate with the token: If a valid token exists, use it to sign in and restore the original user ID.
  4. Save new credentials if needed: If no token exists (or it’s invalid), create a new anonymous user and save their refresh token.

Example Code

using Firebase.Auth;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class EditorAnonymousAuthPersistence : MonoBehaviour
{
    private FirebaseAuth _auth;
    // Unique key to store our refresh token in PlayerPrefs
    private const string EditorRefreshTokenKey = "Firebase_Anonymous_Editor_Token";

    void Awake()
    {
        _auth = FirebaseAuth.DefaultInstance;
        // Initialize persistence logic once Firebase is ready
        _auth.StateChanged += AuthStateChanged;
    }

    private async void AuthStateChanged(object sender, System.EventArgs e)
    {
        // Unsubscribe after first run to avoid repeated calls
        _auth.StateChanged -= AuthStateChanged;

#if UNITY_EDITOR
        string savedToken = PlayerPrefs.GetString(EditorRefreshTokenKey, string.Empty);

        if (!string.IsNullOrEmpty(savedToken))
        {
            try
            {
                // Restore the existing anonymous user
                await _auth.SignInWithRefreshTokenAsync(savedToken);
                Debug.Log($"Restored anonymous user ID: {_auth.CurrentUser.UserId}");
                return;
            }
            catch (FirebaseException ex)
            {
                Debug.LogError($"Failed to restore user: {ex.Message} — generating new user instead.");
                PlayerPrefs.DeleteKey(EditorRefreshTokenKey);
            }
        }

        // No valid token found, create new anonymous user
        var authResult = await _auth.SignInAnonymouslyAsync();
        Debug.Log($"Created new anonymous user ID: {authResult.User.UserId}");
        // Save the refresh token for next session
        PlayerPrefs.SetString(EditorRefreshTokenKey, authResult.User.RefreshToken);
        PlayerPrefs.Save();
#endif
    }

    // Optional: Add a menu item to clear the saved token for testing new users
#if UNITY_EDITOR
    [MenuItem("Firebase/Clear Editor Anonymous User")]
    private static void ClearEditorAnonymousUser()
    {
        PlayerPrefs.DeleteKey(EditorRefreshTokenKey);
        PlayerPrefs.Save();
        Debug.Log("Cleared saved anonymous user token from editor PlayerPrefs.");
    }
#endif
}

Key Notes

  • Isolated to editor: The #if UNITY_EDITOR directives ensure this logic won’t interfere with device builds, where Firebase’s native persistence works as expected.
  • Testability: The menu item (Firebase/Clear Editor Anonymous User) lets you easily reset the user ID when you need to test fresh user scenarios.
  • Token validity: Refresh tokens for anonymous users don’t expire (unless the user is deleted), so this should work reliably across editor sessions.

Just attach this script to a persistent GameObject in your scene (like a Firebase manager) and you’ll have a consistent anonymous user ID every time you launch the Unity editor.

内容的提问来源于stack exchange,提问作者Johnny Christensen

火山引擎 最新活动