Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

unity3d - Save and load data to firebase not working unity

maybe my code will mess here beacuse I'm new into firebase stuff and there is lack doc for newbie like me, so I want to make save and load data from firebase, there is 2 scene the first for main menu and second one the main game,so when firstime login or auto login, user will load current user data from realtime database (I'm using firebase) also applies to user when back to main menu.

in the second scene itself, user load current user highscore data at first start then when game over if the score > lasthighscore that will save/update latest highscore to realtime database.

here the preview this is when I auto-login then playgame until game over:

it's supposed to be updated but not when back to main menu, I already try with player prefs since i erase all data when sign out so the highscore always be 0 and if login with other account that highscore is not belong to other account. here my firebase script on main menu:

   private void Start()
    {
        Time.timeScale = 1;
        mainPanel.SetActive(true);
        InitializeFirebase();
    }

    void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        DBreference = FirebaseDatabase.DefaultInstance.RootReference;
        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);
    }

    void AuthStateChanged(object sender, System.EventArgs eventArgs)
    {
        //This checks if the user (your local user) is the same as the one from the auth
        if (auth.CurrentUser != User)
        {
            //this seems the same, but user could have been null before
            bool signedIn = User != auth.CurrentUser && auth.CurrentUser != null;
            if (!signedIn && User != null)
            {
                Debug.Log("Signed out " + User.UserId);
                loginPanel.SetActive(true);
            }
            //this is important step, this user is the one you should be working with
            User = auth.CurrentUser;
            if (signedIn)
            {
                Debug.Log("Signed in " + User.UserId);
                userNameShowText.text = User.DisplayName;
                StartCoroutine(LoadUserData());
                loginPanel.SetActive(false);

                //            //highScoreMainMenu.text = PlayerPrefs.GetInt("highscore").ToString("0000000");

            }
            else
            {
                loginPanel.SetActive(true);
            }
        }
    }
    
     public IEnumerator Login(string _email, string _password)
    {
        //Call the Firebase auth signin function passing the email and password
        var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
        //Wait until the task completes
        yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);

        if (LoginTask.Exception != null)
        {
            //If there are errors handle them
            Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
            FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
            AuthError errorCode = (AuthError)firebaseEx.ErrorCode;

            string message = "Login Failed!";
            switch (errorCode)
            {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;
                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;
                case AuthError.WrongPassword:
                    message = "Wrong Password";
                    break;
                case AuthError.InvalidEmail:
                    message = "Invalid Email";
                    break;
                case AuthError.UserNotFound:
                    message = "Account does not exist";
                    break;
            }
            warningLoginText.text = message;
        }
        else
        {
            //User is now logged in
            //Now get the result
            User = LoginTask.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
            warningLoginText.text = "";
            confirmLoginText.text = "Logged In";

            StartCoroutine(LoadUserData());

            yield return new WaitForSeconds(2);

            userNameShowText.text = User.DisplayName;
            UserDataScreen(); // Change to user data UI
            confirmLoginText.text = "";
            ClearLoginFeilds();
            ClearRegisterFeilds();
        }
    }

     public IEnumerator UpdateHighScore(int _highScore)
    {
        var DBTask = DBreference.Child("users").Child(auth.CurrentUser.UserId).Child("highscore").SetValueAsync(_highScore);

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
           //giscrore now updated
        }
    }

and this is for the game scene also same function for update higscore like on main menu.

void Start()
    {
        InitializeFirebase();

        YetGameOver();
        //GetScore
        score = 0;
        scoreText.text = score.ToString("00000");
        //highScoreText.text = "HI :" + PlayerPrefs.GetInt("highscore", 0).ToString("00000");
        maxTime = .1f;
    }

   void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        DBreference = FirebaseDatabase.DefaultInstance.RootReference;
        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);
    }

    void AuthStateChanged(object sender, System.EventArgs eventArgs)
    {
        //This checks if the user (your local user) is the same as the one from the auth
        if (auth.CurrentUser != User)
        {
            //this seems the same, but user could have been null before
            bool signedIn = User != auth.CurrentUser && auth.CurrentUser != null;
            if (!signedIn && User != null)
            {
                Debug.Log("Signed out " + User.UserId);
            }
            //this is important step, this user is the one you should be working with
            User = auth.CurrentUser;
            if (signedIn)
            {
                Debug.Log("Signed in " + User.UserId);
                StartCoroutine(LoadUserData());
                //highScoreMainMenu.text = PlayerPrefs.GetInt("highscore").ToString("0000000");

            }
        }
    }

  public void GameOver()
    {
        SaveData();
        StartCoroutine(WaitToDeath());
    }

public void SaveData()
    {
        Debug.Log("Saved");
        StartCoroutine(UpdateHighScore(PlayerPrefs.GetInt("highscore", 0)));
    }

 public IEnumerator WaitToDeath()
    {

        _CamShake.instance.shouldShake = true;

        DeathSound();

        gameOverPanel.SetActive(true);

        endHighScoreText.text = "HI :" + PlayerPrefs.GetInt("highscore").ToString("0000000");
        scoreText.gameObject.SetActive(false);
        highScoreText.gameObject.SetActive(false);

        yield return new WaitForSeconds(.1f);

        //_AdmobAds.instance.ShowInterstitialAd();
        isStarted = false;
        isGameOver = true;
        Time.timeScale = 0;
    }
//same function like main menu
public IEnumerator UpdateHighScore(int _highScore)
    {
        var DBTask = DBreference.Child("users").Child(auth.CurrentUser.UserId).Child("highscore").SetValueAsync(_highScore);

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //highscore are now updated
            
        }
    }

public IEnumerator LoadUserData()
    {
        //Get the currently logged in user data
        var DBTask = DBreference.Child("users").Child(User.UserId).GetValueAsync();

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else if (DBTask.Result.Value == null)
        {
            //No data exists yet
            highScoreText.text = "0";
            endHighScoreText.text = "0";
        }
        else
        {
            //Data has been retrieved
            DataSnapshot snapshot = DBTask.Result;
            highScoreText.text = endHighScoreText.text = snapshot.Child("highscore").Value.ToString();
        }
    }

question from:https://stackoverflow.com/questions/65951477/save-and-load-data-to-firebase-not-working-unity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...