Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Can't update MySQL database when the user force quits the app

Discussion in 'Scripting' started by shivam3d, Jul 24, 2017.

  1. shivam3d

    shivam3d

    Joined:
    Nov 13, 2012
    Posts:
    10
    I need to change the value of a field in an online MySQL database as soon as the player leaves the app. This happens perfectly if the user uses the UI 'X' button. However, if the user force quits the app using native Android controls then the database is not updated. I've tried using onDestroy. However, before the code in that function is executed, the app is destroyed.

    The variable needs to be changed upon the closing of the app. This is because we are maintaining the number of online players in this database. When the user opens the app, we increment the MySQL field. When the user quits the app, we intend to decrement that variable's value to get the accurate online user information.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You can't. In pretty much any platform the user has ultimate control over your app running, and you should assume they can and will terminate it on a whim mid process. Even if you could guarantee a callback on application quit, you will never be able to control a user disconnecting from the network or experiencing a power failure.

    Good news is there are alternative structures you can use to get the player count. One option is to send a keep alive signal at a regular frequency. If you don't get the signal, you can drop the player from your count.
     
  3. shivam3d

    shivam3d

    Joined:
    Nov 13, 2012
    Posts:
    10
    How do I do this?

    Can't find a documentation on this.
     
    Last edited: Jul 24, 2017
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    I would send a request to your sql database at some defined interval (the exact interval is highly game dependent). This can simply add a record to a table with the current timestamp.

    Then whenever you need to check the current player count, dump everything in the table with a timestamp before the current time less your keep alive interval. The number of currently active players is the number of records left in the table.