Unity Pauses when attempting to post to MongoDB

okay so I’m trying to get Unity to post data to my MongoDB realm with the SDK. My game has a mini game inside of it, and when the mini game ends (timeleft == 0), it should pull the data from that attempt (score, etc) and send it to the database.
However, instead of doing this, it’s pausing the game (not freezing or slowing, literally pausing, as if I clicked the pause button). It’s also not being received by my database.

Code below:


using System;
using UnityEngine;
using Realms;
using Realms.Sync;
using MongoDB.Bson;

public class DBcontrol : MonoBehaviour
{

    private int points;
    private int GameOver;
    private float ticktock;
    /*  public App app;
      public User user;
      public PartitionSyncConfiguration config;
      public Realm realm;*/
    public static DBcontrol Instance;
    public string RealmAppId = "PRIVATE INFO";
    private Realm _realm;
    private App _realmApp;
    private User _realmUser;
void Awake()
    {
        DontDestroyOnLoad(gameObject);
        Instance = this;
    }
void OnEnable(){
_realm = Realm.GetInstance();
}
    void OnDisable()
    {
        if (_realm != null)
        {
            _realm.Dispose();
        }
    }

    void Start()
    {
        _realmApp = App.Create(new Realms.Sync.AppConfiguration(RealmAppId));
        points = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().scorevar;
        GameOver = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().idle;
        ticktock = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().timeLeft;
        /*    app = http://Realms.Sync.App.Create("private token");
            user = new http://Realms.Sync.App.LogInAsync(Credentials.Anonymous());
            config = new Realms.Sync.PartitionSyncConfiguration("ETH_inbox", user);
            realm = Realms.Sync.GetInstanceAsync(config);*/
    }

    void Update()
    {
        int GameOver = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().idle;
        float ticktock = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().timeLeft;
        string date = http://System.DateTime.Now.ToString("http://dd.MM.yyyy");
        string time = http://System.DateTime.Now.ToString("http://HH.mm.ss");
        if (ticktock <= 0)
        {
          _playerprofile = new DataBlueprint
        (
          "test.eth",        GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().scorevar,
          "@test",
          ("[" + date + "], <" + time + ">"),
          "69420gm",
          42069
        );
          _realm.Write(() =>
          {
          _realm.Add(_playerProfile);
          });
            Debug.Log("successfully recorded attempt");
        }
    }
//}

Okay, there are two issues here:

  1. You’re opening a local Realm rather than a synchronized one - in OnEnable, you’re calling _realm = Realm.GetInstance(), which will just store data locally on your device. I’m assuming this is why you’re not seeing the data ever get uploaded to the server. You can refer to the docs for how to authenticate a user and open a synchronized Realm.
  2. The game pausing issue - I don’t see anything obvious that would cause your game to pause. Based on some reading, looks like either Debug.Break() or EditorApplication.isPaused = true will cause the game to pause. Can you grep your code and see if you accidentally have anything like that?

If you can send us a repro for the pausing issue - either a small project that reproduces it or your project (we can send you a private upload link if you choose that path), then we’d be happy to take over and debug that further.

2 Likes

As @nirinchev said, I would also like to see the project if I can. Nothing is standing out in what you’ve provided, but maybe there are some pieces missing.

Also I did notice that you have a member ticktock variable for your class, but you’re also redefining it in your Update method. I’m not sure if Unity is going to spazz out or not.

Is there anything popping up in your logs? Also have you tried Realm Studio on your local database to decipher what’s going on?

1 Like

I’ll try correcting the local vs synced issue first, and then see if the pausing bug persists. If it does, then I’ll send you the files so you can try reproducing the issue.

Just to confirm, the correct way to connect is realms.getInstanceAsync?

It’s redefining in Update() because the variable is a countdown, so I’m trying to get the new value as often as possible. To be honest, it annoys me a bit too, but if there’s any other ways to do it, I’d love to hear them. Should I delete the “float” prefix to optimize performance?

My debug logs in Unity just show attempt recorded successfully, which isn’t true, and also closed all instances when I quit the game, as expected.

I haven’t tried the realms studio.

Not only - you need to login a user and then create a SyncConfiguration that you then pass to your Realm.GetInstance or Realm.GetInstanceAsync method. It should look something like:

_realmUser = _realmApp.CurrentUser;
if (_realmUser == null)
{
    // Login a user - you can also use other credential types
    // It might also be a good idea to that at an earlier stage so that you're
    // guaranteed to have a user when you enter the minigame
    _realmUser = await _realmApp.LogInAsync(Credentials.Anonymous());
}

var config = new PartitionSyncConfiguration("ETH_inbox", user);
realm = Realm.GetInstance(config);
2 Likes

I made the changes. This fixed the pausing error, and I can resume playing after finishing the minigame. However, the data is still not being sent to the db. I tried login in from both Start() and OnEnable(). Both had the same result.
All that’s left is successfully posting to db.

using System;
using UnityEngine;
using Realms;
using Realms.Sync;
using MongoDB.Bson;

public class DBcontrol : MonoBehaviour
{
    private int points;
    private int GameOver;
    private float ticktock;
    public static DBcontrol Instance;
    public string RealmAppId = "no";
    private Realm _realm;
    private App _realmApp;
    private User _realmUser;
    public DataBlueprint _playerprofile;
    private int iterations = 0;
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        Instance = this;
    }
    void OnDisable()
    {
        if (_realm != null)
        {
            _realm.Dispose();
        }
    }

    async void Start()
    {
      _realmUser = _realmApp.CurrentUser;
      if (_realmUser == null)
      {
          _realmUser = await _realmApp.LogInAsync(Credentials.Anonymous());
      }

      var config = new PartitionSyncConfiguration("ETH_inbox", _realmUser);
      _realm = Realm.GetInstance(config);
        _realmApp = App.Create(new Realms.Sync.AppConfiguration(RealmAppId));
        points = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().scorevar;
        GameOver = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().idle;
        ticktock = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().timeLeft;
    }

    void Update()
    {
        int GameOver = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().idle;
        float ticktock = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().timeLeft;
        string date = System.DateTime.Now.ToString("dd.MM.yyyy");
        string time = System.DateTime.Now.ToString("HH.mm.ss");
        points = GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().scorevar;
        if (ticktock <= 0){

        /*  _playerprofile = new DataBlueprint
        (
          "test.eth",
          GameObject.Find("FPlayer").GetComponent<RightClickSaveAs>().scorevar,
          "@test",
          ("[" + date + "], <" + time + ">"),
          "69420gm",
          42069
        );*/
          _realm.Write(() =>
          {
          _playerprofile = _realm.Add(new DataBlueprint("test.eth", points, "@test", ("[" + date + "], <" + time + ">"), "69420gm", 42069));
          });
    
            //Debug.Log(_playerprofile.ToString());
            Debug.Log("successfully recorded attempt");
            };

        }
    }
//}

Just to confirm, when you say it is not posting to the database, are you saying it is not appearing in MongoDB Atlas or it is not appearing in your local Realm database?

I can’t find it in any of my atlas collections on the MongoDB browser UI or Compass. Metrics measure 0 data transfer on both Atlas


And realms

Hi @Anon123,

Can you please download Realm Studio:

https://studio-releases.realm.io/

With Realm Studio, open the local Realm database for your game. Let’s ignore the MongoDB Cloud for now.

I don’t have the exact answer on where the local Realm database would be stored on your computer, but for me, my database is stored here:

/Users/nicolas.raboy/Library/Application Support/MongoDB/Mongo World/mongodb-realm/mongo_world_demo-ebxbj/61928794a3efdfc437002536

You’re looking for a .realm file and it can be opened with Realm Studio. We basically want to see if data is even making it into your local Realm database. If it isn’t making it into your local Realm database, it isn’t going to make it into your remote collections.

Need to pinpoint the failure spot and go from there.

Hopefully that makes sense.

Best,


Is this it? Old realm document from 3 days ago, before I even asked for help. I can’t find any other realm documents, so have my new changes somehow (for lack of a better term) broke the code?

Also, after trying to change a setting with the timer in my minigame, I couldn’t connect to the db, getting the following error as well.

translator failed to complete processing batch: failed to update resume token document: server selection error: server selection timeout, current topology: { Type: ReplicaSetNoPrimary, Servers: [{ Addr: v-1-shard-00-00.kdslj.mesh.mongodb .net:30460, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 127.0.0.1:30460: connect: connection refused }, { Addr: v-1-shard-00-01.kdslj.mesh.mongodb .net:30460, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 127.0.0.1:30460: connect: connection refused }, { Addr: v-1-shard-00-02.kdslj.mesh.mongodb .net:30460, Type: Unknown, Last error: connection() error occured during connection handshake: dial tcp 127.0.0.1:30460: connect: connection refused }, ] }
Source:
Error syncing MongoDB write

I decided it would be better if I stopped making edits until getting some more advice from you.

Hey @Anon123,

The path looks like it is probably correct. Only you would know if the data looks right :-).

If the data is just test data, try removing the parent directory to the .realm file or the DefaultCompany directory. This will allow your Unity application to create and start with a fresh database next time it runs. While not at all common, something could have gotten botched at some point during development.

I’m not too sure what the timeout errors are in the context of Realm. Maybe @nirinchev or @Dominic_Frei would know.

At least we have a starting point though! The point of failure is with interactions of your local database, hence why you’re not seeing anything in the cloud.

To keep you busy over the weekend, take a look at one of my more recent Unity with Realm projects:

This might give you ideas into the problem or even optimization of the code.

Let me know how it goes.

Best,

Thank you, I will read the docs you sent me.

should I try writing the login as an async function?

I’m afraid this discussion is getting a little all over the place. The last code snippet you posted has the following code in Start:

_realmUser = _realmApp.CurrentUser;
if (_realmUser == null)
{
    _realmUser = await _realmApp.LogInAsync(Credentials.Anonymous());
}

var config = new PartitionSyncConfiguration("ETH_inbox", _realmUser);
_realm = Realm.GetInstance(config);
_realmApp = App.Create(new Realms.Sync.AppConfiguration(RealmAppId));

which doesn’t make a lot of sense to me considering you’re creating the _realmApp after you use it to log the user in. Are you certain that this code is correct and what your app is actually executing?

On the topic of where your file is located, you can log config.DatabasePath - it will tell you the correct local path of the Realm file.

Finally, you should increase the log level by setting Realms.Logging.Logger.LogLevel = Realms.Logging.LogLevel.All - this should output operational logs from Sync in the Unity console and give us more insight into issues when connecting to the server.

so
1.) change verbosity level of debugger
2.) create _realmApp before attempting user login
3.) log where local realm files are being stored debug.log(config.databasepath)