You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2022中FirebaseAuth登录成功后无法切换场景求助

问题原因与解决方案

问题出在Firebase异步任务的回调线程上:SignInWithEmailAndPasswordAsync的ContinueWith回调默认运行在后台线程,而Unity的SceneManager.LoadScene属于Unity主线程专属API,后台线程调用这类API不会执行,也不会抛出可见错误,就会出现你遇到的“代码看似存在但无效果”的情况。

解决方案1:使用Firebase提供的主线程回调方法

Firebase Unity SDK提供了ContinueWithOnMainThread扩展方法,可以直接将回调逻辑切换到Unity主线程执行,这是最简单的方案:

using Firebase.Extensions; // 需添加此命名空间引用

public void Init()
{
    FirebaseAuth auth = FirebaseAuth.DefaultInstance;

    auth.SignInWithEmailAndPasswordAsync(mail, password).ContinueWithOnMainThread(task => {
        if (task.IsCompleted && !task.IsCanceled && !task.IsFaulted)
        {
            Debug.Log("Login successful!");
            SceneManager.LoadScene("Principal"); 
        }
        else
        {
            Debug.Log("Login failed: " + task.Exception);
        }
    });
}

如果找不到ContinueWithOnMainThread,检查Firebase Unity SDK是否完整导入,确保相关扩展包已包含在内。

解决方案2:自定义主线程任务队列

如果不想依赖Firebase的扩展方法,可以自己实现一个主线程调度器,将场景加载逻辑放到主线程执行:

首先创建全局主线程调度类:

using System.Collections.Generic;
using UnityEngine;

public class MainThreadDispatcher : MonoBehaviour
{
    private static MainThreadDispatcher _instance;
    private static Queue<System.Action> _tasks = new Queue<System.Action>();

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void Update()
    {
        lock (_tasks)
        {
            while (_tasks.Count > 0)
            {
                _tasks.Dequeue().Invoke();
            }
        }
    }

    public static void Enqueue(System.Action action)
    {
        lock (_tasks)
        {
            _tasks.Enqueue(action);
        }
    }
}

然后修改登录脚本,将场景加载逻辑加入主线程队列:

public void Init()
{
    FirebaseAuth auth = FirebaseAuth.DefaultInstance;

    auth.SignInWithEmailAndPasswordAsync(mail, password).ContinueWith(task => {
        if (task.IsCompleted && !task.IsCanceled && !task.IsFaulted)
        {
            Debug.Log("Login successful!");
            // 把场景加载逻辑丢到主线程执行
            MainThreadDispatcher.Enqueue(() => {
                SceneManager.LoadScene("Principal");
            });
        }
        else
        {
            Debug.Log("Login failed: " + task.Exception);
        }
    });
}

注意要在初始场景中添加一个挂载了MainThreadDispatcher脚本的GameObject,确保它在场景切换时不会被销毁。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 16:03:08