Skip to content

Unity Editor Freezes on Reloading Assemblies (2019.2.01f, Firebase 6.3.0) #449

Closed
@staythirsty90

Description

@staythirsty90

Unity will refresh and occasionally place unity in a state that would cause it to freeze if I reload assemblies by entering play mode or compiling a script

I noticed in the unity console these two messages:

Listen at Leaders failed: Permission denied
UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:LogWarning(Object)
Firebase.Platform.FirebaseLogger:LogMessage(PlatformLogLevel, String) (at Z:\tmp\tmp.SOETccsZXr\firebase\app\client\unity\src\Unity\FirebaseLogger.cs:76)
Firebase.LogUtil:LogMessage(LogLevel, String) (at Z:\tmp\tmp.HzqjZMMOFf\firebase\app\client\unity\proxy\LogUtil.cs:62)
Firebase.LogUtil:LogMessageFromCallback(LogLevel, String) (at Z:\tmp\tmp.HzqjZMMOFf\firebase\app\client\unity\proxy\LogUtil.cs:70)
 
(Filename: Z:/tmp/tmp.SOETccsZXr/firebase/app/client/unity/src/Unity/FirebaseLogger.cs Line: 76)

This client does not have permission to perform this operation.
UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:LogError(Object)
UIHandler:OnValueChanged(Object, ValueChangedEventArgs) (at Assets\Scripts\UI\UIHandler.cs:116)
Firebase.Database.Internal.<OnCancelledHandler>c__AnonStorey1:<>m__0() (at Z:\tmp\tmp.kBuvbLryUE\firebase\database\client\unity\proxy\InternalValueListener.cs:58)
Firebase.ExceptionAggregator:Wrap(Action) (at Z:\tmp\tmp.SOETccsZXr\firebase\app\client\unity\src\Platform\ExceptionAggregator.cs:98)
Firebase.Database.Internal.InternalValueListener:OnCancelledHandler(Int32, Error, String) (at Z:\tmp\tmp.kBuvbLryUE\firebase\database\client\unity\proxy\InternalValueListener.cs:51)
Firebase.AppUtilPINVOKE:PollCallbacks()
Firebase.AppUtil:PollCallbacks() (at Z:\tmp\tmp.HzqjZMMOFf\firebase\app\client\unity\proxy\AppUtil.cs:32)
Firebase.Platform.FirebaseAppUtils:PollCallbacks() (at Z:\tmp\tmp.HzqjZMMOFf\firebase\app\client\unity\proxy\FirebaseAppUtils.cs:17)
Firebase.Platform.FirebaseHandler:Update() (at Z:\tmp\tmp.SOETccsZXr\firebase\app\client\unity\src\Unity\FirebaseHandler.cs:189)
Firebase.Platform.FirebaseEditorDispatcher:Update() (at Z:\tmp\tmp.SOETccsZXr\firebase\app\client\unity\src\Unity\FirebaseEditorDispatcher.cs:86)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions() (at C:\buildslave\unity\build\Editor\Mono\EditorApplication.cs:303)
 
(Filename: Assets/Scripts/UI/UIHandler.cs Line: 116)

Once I see these messages I know that I must close Unity otherwise entering play mode or making any edits to my scripts would cause Unity to freeze. The last message in the editor log is:

Begin MonoManager ReloadAssembly

I imagine I implemented Auth & Database incorrectly:

using Firebase;
using Firebase.Auth;
using Firebase.Database;
using Firebase.Unity.Editor;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIHandler : MonoBehaviour {

    public Text text;
    FirebaseAuth auth;
    FirebaseUser user;
    DatabaseReference reference;
    ArrayList leaderBoard;
    private const int MaxScores = 5;
    private int score = 0;
    private uint currentCoins = 0;
    public delegate void ShowLeaderboardHandler(ArrayList leaderboard);
    public event ShowLeaderboardHandler OnShowLeaderboard;

    DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;

    string databaseName = "Leaders";

    void OnDestroy() {
        Debug.Log("UIHANDLER ON DESTORY");
        auth.StateChanged -= AuthStateChanged;
        auth = null;
        user = null;
        FirebaseDatabase.DefaultInstance.GetReference(databaseName).ValueChanged -= OnValueChanged;
    }

    void Start() {
        leaderBoard = new ArrayList();
        leaderBoard.Add("Firebase Top " + MaxScores.ToString() + " Scores");

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available) {
                InitializeFirebaseAndLeaderboard();
            }
            else {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
    }

    // Initialize the Firebase database:
    void InitializeFirebaseAndLeaderboard() {
        FirebaseApp app = FirebaseApp.DefaultInstance;
        app.SetEditorDatabaseUrl("https://xyz.firebaseio.com/");
        if (app.Options.DatabaseUrl != null)
        {
            app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
        }
        StartListener();
        auth = FirebaseAuth.DefaultInstance;
        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);
        reference = FirebaseDatabase.DefaultInstance.RootReference;
        if (user == null) {
            SigninAnonymously();
        }
    }

    protected void StartListener() {
        Debug.Log("START LISTENER");
        FirebaseDatabase.DefaultInstance
          .GetReference(databaseName).OrderByChild("score")
          .ValueChanged += OnValueChanged;
    }

    void OnValueChanged(object sender2, ValueChangedEventArgs e2){
        if (e2.DatabaseError != null)
        {
            Debug.LogError(e2.DatabaseError.Message);
            return;
        }
        
        string title = leaderBoard[0].ToString();
        leaderBoard.Clear();
        leaderBoard.Add(title);
        if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0)
        {
            foreach (var childSnapshot in e2.Snapshot.Children)
            {
                if (childSnapshot.Child("score") == null || childSnapshot.Child("score").Value == null)
                {
                    Debug.LogError("Bad data in sample.  Did you forget to call SetEditorDatabaseUrl with your project id?");
                    break;
                }
                else
                {
                    if (user.UserId == childSnapshot.Child("id").Value.ToString())
                    {
                        FindObjectOfType<Score>().LoadHighScore(int.Parse(childSnapshot.Child("score").Value.ToString()));
                    }
                    leaderBoard.Insert(1, childSnapshot.Child("score").Value.ToString());
                }
            }
        }
    }
             
    public void ShowLeaderboard() {
        Debug.Log("SHOW LEADERBOARD");
        OnShowLeaderboard?.Invoke(leaderBoard);
    }

    // Track state changes of the auth object.
    void AuthStateChanged(object sender, System.EventArgs eventArgs) {
        Debug.Log("AUTH STATE CHANGED");
        if (auth.CurrentUser != user) {
            bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
            user = auth.CurrentUser;
            if (signedIn) {
                if (text) {
                    text.text = user.UserId;
                }
            }
        }
    }

    // Attempt to sign in anonymously.
    public void SigninAnonymously() {
        Debug.Log("SIGN IN ANONYMOUSLY");
        auth.SignInAnonymouslyAsync().ContinueWith(task => {
            if (task.IsCompleted && !task.IsCanceled && !task.IsFaulted) {
               // Debug.Log("User is now signed in.");
                user = task.Result;
            }
            else if (task.IsFaulted || task.IsCanceled) {
               // Debug.Log("User signin failed");
            }
        });
    }
 
    TransactionResult AddScoreToLeaderboardTransaction(MutableData mutableData) {
        Debug.Log("ADD SCORE TO LEADERBOARD TRANSACTION");
        List<object> leaders = mutableData.Value as List<object>;

        if (leaders == null) {
            leaders = new List<object>();
        }
        int index = -1;
        //int childScore;
        //int childCoins;
        for (int i = 0; i < leaders.Count; i++) {

            var data = (Dictionary<string, object>)leaders[i];
            string id = (string)data["id"];
            if (id.Equals(user.UserId)) {
                int s = int.Parse(data["score"].ToString());
                if (s >= score) {
                    return TransactionResult.Abort();
                }
                index = i;
                break;
            }
        }
        if (index > -1) {
            leaders.RemoveAt(index);
            leaders.Add(new Dictionary<string, object> { ["id"] = user.UserId, ["score"] = score });
            mutableData.Value = leaders;
            return TransactionResult.Success(mutableData);
        }
        else {
            // user hasn't been on the leaderboard yet
            leaders.Add(new Dictionary<string, object> { ["id"] = user.UserId, ["score"] = score });
            mutableData.Value = leaders;
            return TransactionResult.Success(mutableData);
        }
    }

    public void AddScore(uint score) {
        this.score = (int)score;
        if (score == 0 ){//|| string.IsNullOrEmpty(email)) {
            return;
        }
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference(databaseName);
        reference.RunTransaction(AddScoreToLeaderboardTransaction).ContinueWith(task => {
              if (task.Exception != null) {
                  //Debug.Log(task.Exception.ToString());
              }
              else if (task.IsCompleted) {
                  //Debug.Log("Transaction complete.");
              }
              else if (task.IsFaulted) {
                 // Debug.Log("Transaction cancelled.");
              }
          });
    }
}

Unity editor version: 2019.2.01f
Firebase Unity SDK version: 6.3.0 using Auth & Database
No additional SDKs
Windows 10
Targeting Android 4.1 (API 16), ARMv7, ARMv64, .NET 4.x, IL2CPP

I haven't tried to reproduce this issue with the Firebase Unity quickstarts but I have tried to re-import all the files without luck

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions