How to write the value of the counter variable in the sqlite database in unity? snippet code:

if (hit.transform.CompareTag("PickUp")) { device++; Destroy(hit.transform.gameObject); if (Application.Quit ()) { Application.dataPath + "/stydent.db3"; } } 

There is a devise variable, which is incremented each time a certain event is executed. It is necessary to record the final result of this variable when exiting the program.

  • Do not know how to write in the database or how to write on exit? - codename0082016
  • @ codename0082016 writing in db - nika.brown09

2 answers 2

To catch an exit event from an application, use OnApplicationQuit automatically in all Monobehaviour scripts, but you need to declare it.

 void OnApplicationQuit(){} 

Further Application.dataPath + "/stydent.db3"; This is generally just a string. If you need to save to the sql database, you either need to write your own plugin, which in the background will record some parameters, and receive them from calls to Unity via CallStatic (or find ready). In this regard, google, well, or here there is a small article on this topic

ps But keep in mind that OnApplicationQuit is called only, you call Application.Quit() OnApplicationQuit Application.Quit() , that is, let's say the user pressed the exit button, you must call this function. And also the user can complete it incorrectly, through the dispatcher, or it will "fly out", and OnApplicationQuit will not work.

    Are you using a sqlite plugin? If yes, then everything is quite simple:

    When you connect a database, you create a connection to it and hash it:

     private SQLiteConnection _connection; _connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite); 

    dbPath - path to the base, including its name. The second parameter is the type of connection. In the database you have the so-called Table - tables with specific columns. Create in unity a class with the same parameters as in the desired table. For example, if you need only a parameter and its value:

     using SQLite4Unity3d; public class PARAMS { [PrimaryKey, AutoIncrement, NotNull] public string PARAM { get; set; } [NotNull] public int VALUE{ get; set; } public override string ToString() { return string.Format ( "[mess: Param= {0}, " + "value: {1}.]", PARAM , VALUE ); } } 

    To add to DB, the following call is made:

      public void InsertParam(string param, int value) { var p = new PARAMS { PARAM = param, VALUE = value }; _connection.Insert(p); } 

    Accordingly, as they said a little higher, if the application closes urgently, then void OnApplicationQuit () {} will not work. Therefore, it is best to save the value immediately after it changes.