База данных Sqlite игры Unity действует по-разному при запуске на устройстве Android - PullRequest
0 голосов
/ 26 октября 2018

Я реализовал базу данных SQLite в своем проекте Unity, и он отлично работает в редакторе Unity. Но когда я запускаю его на базе Android, операции с базами данных ведут себя странно.

Имеется главное меню, в котором пользователь может выбрать каждую из 4 игр и играть в них. Я рассчитываю общее время, которое пользователь проводит в игре. Поэтому я добавил таймер для каждой игры и поместил счетчик таймера в базу данных, а затем, когда пользователь наносит ответный удар, вычисляет сумму общего времени.

В редакторе Unity он отлично показывает последнее добавленное общее время в главном меню. но в андроиде, когда пользователь возвращается в главное меню, общее время отдыхает. Он не выполняет операцию суммирования на Android.

Но когда я выполняю операцию в той же сцене, она работает и на Android.

Я все сделал правильно при компиляции SQLite для Android. Я добавил свой файл БД в StreamingAssets и добавил все необходимые плагины.

Вот мой код и структура файла.

enter image description here

Timer.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Data;
using Mono.Data.Sqlite;
using UnityEngine.UI;
using System.IO;

public class Timer : MonoBehaviour {

    public Text timerText;
    private float startTime;

    private string connectionString;

    string minutes;
    string seconds;
    string a;
    float t;

    float DailyTime;

    string CurrentDate;

    // Use this for initialization
    void Start () {
        string filepath = Application.persistentDataPath + "/" + "trackerDB2.sqlite";
        //  // if it doesn't ->

        //  // open StreamingAssets directory and load the db ->

        WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "trackerDB2.sqlite");  // this is the path to your StreamingAssets in android

        while(!loadDB.isDone) {}  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
        //  // then save to Application.persistentDataPath

        File.WriteAllBytes(filepath, loadDB.bytes);
        connectionString = "URI=file:" + filepath;
        //connectionString = "URI=file:" + Application.dataPath +  "/StreamingAssets/" + "trackerDB2.sqlite";

        startTime = Time.time;



        PlayerPrefs.SetString("date_time", System.DateTime.Now.ToString("yyyy-MM-dd")); 
        CurrentDate = PlayerPrefs.GetString("date_time");
    }

    // Update is called once per frame
    void Update () {
        t = Time.time - startTime;

        //PlayerPrefs.SetFloat ("RowTime",t);

        minutes = ((int)t / 60).ToString ();
        seconds = (t % 60).ToString ("f0");


        PlayerPrefs.SetString ("TimeKey", minutes + ":" + seconds);
        timerText.text =PlayerPrefs.GetString("TimeKey");
        a = minutes;
    }

    public void AddEvent(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("INSERT INTO events(date,timer_count) VALUES({0},{1})",System.DateTime.Now.ToString("yyyy-MM-dd"),t);
                dbCmd.CommandText = sqlQuery;
                dbCmd.ExecuteScalar();
                dbConnection.Close();
            }
        }

        PlayerPrefs.SetString("date_time", System.DateTime.Now.ToString("yyyy-MM-dd")); 
        Debug.Log(PlayerPrefs.GetString("date_time"));
    }

    public void GetSum(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("SELECT SUM(timer_count) FROM events WHERE date={0}",CurrentDate);
                dbCmd.CommandText = sqlQuery;

                using (IDataReader reader = dbCmd.ExecuteReader ()) {
                    while (reader.Read ()) {
                        DailyTime = reader.GetFloat (0);
                    }

                    dbConnection.Close();
                    reader.Close ();
                }


            }
        }

    }

    public void AddDailyEvent(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("UPDATE daily_events SET timer_count={0} WHERE date={1}",DailyTime,CurrentDate);
                dbCmd.CommandText = sqlQuery;
                dbCmd.ExecuteScalar();
                dbConnection.Close();
            }
        }
    }
}

SetDateRow.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Data;
using Mono.Data.Sqlite;
using UnityEngine.UI;
using System.IO;

public class SetDateRow : MonoBehaviour {

    private string connectionString;

    string SqliteDailyDate;
    string SqliteEventsDate;
    float TheTime;

    string CurrentDate;

    public Text DataText;

    // Use this for initialization
    void Start () {
        string filepath = Application.persistentDataPath + "/" + "trackerDB2.sqlite";
        //  // if it doesn't ->

        //  // open StreamingAssets directory and load the db ->

        WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "trackerDB2.sqlite");  // this is the path to your StreamingAssets in android

        while(!loadDB.isDone) {}  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
        //  // then save to Application.persistentDataPath

        File.WriteAllBytes(filepath, loadDB.bytes);
        connectionString = "URI=file:" + filepath;
        //connectionString = "URI=file:" + Application.dataPath +  "/StreamingAssets/" + "trackerDB2.sqlite";


        AddEvent ();
        AddFirstEvent ();

        PlayerPrefs.SetString("date_time", System.DateTime.Now.ToString("yyyy-MM-dd")); 
        CurrentDate = PlayerPrefs.GetString("date_time");
    }

    // Update is called once per frame
    void Update () {
    //  GetEvent ();
    }

    //Add new event with o timer at the start of the game
    public void AddEvent(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("INSERT INTO events(date,timer_count) VALUES({0},0)",System.DateTime.Now.ToString("yyyy-MM-dd"));
                dbCmd.CommandText = sqlQuery;
                dbCmd.ExecuteScalar();
                dbConnection.Close();
            }
        }

        PlayerPrefs.SetString("date_time", System.DateTime.Now.ToString("yyyy-MM-dd")); 
        Debug.Log(PlayerPrefs.GetString("date_time"));
    }

    //get the last added date of events from daily events table which has the total sum of the time that user played each game
    public void GetDateDailyEvents(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("SELECT date FROM daily_events ORDER BY eventID DESC LIMIT 1");
                dbCmd.CommandText = sqlQuery;

                using (IDataReader reader = dbCmd.ExecuteReader ()) {
                    while (reader.Read ()) {
                        SqliteDailyDate = reader.GetString (0);
                    }

                    dbConnection.Close();
                    reader.Close ();
                }


            }
        }
    }


    //get the last added date from events table which has timer count of each event seperately
    public void GetDateEvents(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("SELECT date FROM events ORDER BY event_id DESC LIMIT 1");
                dbCmd.CommandText = sqlQuery;

                using (IDataReader reader = dbCmd.ExecuteReader ()) {
                    while (reader.Read ()) {
                        SqliteEventsDate = reader.GetString (0);
                    }

                    dbConnection.Close();
                    reader.Close ();
                }


            }
        }
    }


    public void AddFirstEvent(){
        GetDateDailyEvents ();
        GetDateEvents ();
        Debug.Log ("daily" + SqliteDailyDate);
        Debug.Log (SqliteEventsDate);
        //check if the last date of events table is equal to the last date of daily events table.
        if (SqliteDailyDate != SqliteEventsDate) {
            using (IDbConnection dbConnection = new SqliteConnection (connectionString)) {
                dbConnection.Open ();
                //if not equal a new event to daily events table will be added
                using (IDbCommand dbCmd = dbConnection.CreateCommand ()) {
                    string sqlQuery = String.Format ("INSERT INTO daily_events(date,timer_count) VALUES({0},0)", System.DateTime.Now.ToString ("yyyy-MM-dd"));
                    dbCmd.CommandText = sqlQuery;
                    dbCmd.ExecuteScalar ();
                    dbConnection.Close ();
                }
            }

        }


        PlayerPrefs.SetString("date_time", System.DateTime.Now.ToString("yyyy-MM-dd")); 
        Debug.Log(PlayerPrefs.GetString("date_time"));
    }

    public void ShowData(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("SELECT timer_count FROM daily_events WHERE date={0}",SqliteDailyDate);
                dbCmd.CommandText = sqlQuery;

                using (IDataReader reader = dbCmd.ExecuteReader ()) {
                    while (reader.Read ()) {
                        DataText.text = reader.GetFloat (0).ToString();
                    }

                    dbConnection.Close();
                    reader.Close ();
                }


            }
        }
    }


    public void GetEvent(){
        using (IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCmd = dbConnection.CreateCommand()){
                string sqlQuery = String.Format("SELECT timer_count FROM daily_events WHERE date={0}",CurrentDate);
                dbCmd.CommandText = sqlQuery;

                using (IDataReader reader = dbCmd.ExecuteReader ()) {
                    while (reader.Read ()) {
                        DataText.text = reader.GetFloat (0).ToString();
                    }

                    dbConnection.Close();
                    reader.Close ();
                }


            }
        }
    }

}

Пожалуйста, помогите мне решить эту проблему.

1 Ответ

0 голосов
/ 26 октября 2018

Кажется, вы переписываете свою базу данных каждый раз при запуске.

File.WriteAllBytes(filepath, loadDB.bytes);

Предлагаю добавить проверку, если файл БД уже существует, не переписывать его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...