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

Firebase创建用户后无法调用SetActive(false)隐藏Panel_Register的问题咨询

解决Firebase注册成功后无法隐藏Panel_Register的问题

我帮你分析下问题所在,其实核心原因是Firebase的异步回调默认跑在后台线程,而Unity所有的UI操作(包括SetActive)都必须在主线程执行,直接在回调里调用就会失效。下面给你具体的解决方案:

核心修复步骤

  • 改用主线程回调:Firebase为Unity专门提供了ContinueWithOnMainThread方法,能确保回调逻辑在Unity主线程执行,这样UI操作就能正常生效了。
  • 检查组件引用:确认你已经在Unity Inspector面板中把Panel_Register对象正确拖到脚本对应的字段上,避免出现空引用的情况。
  • 验证回调执行:可以在回调成功的代码块里加个Debug日志,确认注册成功后确实走到了隐藏面板的逻辑。

修改后的完整代码

using UnityEngine;
using UnityEngine.UI;
using Firebase.Auth;

public class RegisterManager : MonoBehaviour
{
    public Text email; 
    public Text password; 
    public GameObject Panel_Register; 

    void Start() { } 

    public void Register() 
    { 
        FirebaseAuth.DefaultInstance.CreateUserWithEmailAndPasswordAsync(email.text, password.text)
            // 改用ContinueWithOnMainThread确保在主线程执行UI操作
            .ContinueWithOnMainThread(task => { 
                if (task.IsCanceled) { 
                    Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled."); 
                    return; 
                } 
                if (task.IsFaulted) { 
                    Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception); 
                    return; 
                } 
                // Firebase user has been created. 
                FirebaseUser newUser = task.Result; 
                Debug.LogFormat("Firebase user created successfully: {0} ({1})", newUser.DisplayName, newUser.UserId); 
                
                // 现在可以正常隐藏面板了
                if(Panel_Register != null)
                {
                    Panel_Register.SetActive(false);
                }
                else
                {
                    Debug.LogError("Panel_Register reference is null!");
                }
            }); 
    }
}

另外,如果你想实现「仅登录用户才能打开新场景」的功能,可以在场景加载前先检查Firebase当前是否有已登录的用户:

public void LoadMainScene()
{
    FirebaseUser currentUser = FirebaseAuth.DefaultInstance.CurrentUser;
    if(currentUser != null)
    {
        // 用户已登录,加载场景
        UnityEngine.SceneManagement.SceneManager.LoadScene("MainScene");
    }
    else
    {
        Debug.Log("Please login first!");
        // 可以弹出提示或者跳转到登录界面
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:31:11