Unity中數據存儲和讀取可以通過多種方式實現,以下是一些常用的方法:
// 存儲數據
PlayerPrefs.SetInt("Score", 100);
// 讀取數據
int score = PlayerPrefs.GetInt("Score");
// 寫入數據
string data = "Hello, World!";
File.WriteAllText("data.txt", data);
// 讀取數據
string data = File.ReadAllText("data.txt");
// 創建數據庫連接
SQLiteConnection connection = new SQLiteConnection("data source=database.db");
connection.Open();
// 創建表
string query = "CREATE TABLE IF NOT EXISTS PlayerData (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)";
SQLiteCommand command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();
// 插入數據
query = "INSERT INTO PlayerData (name, score) VALUES ('Player1', 100)";
command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();
// 查詢數據
query = "SELECT * FROM PlayerData";
command = new SQLiteCommand(query, connection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string name = reader["name"].ToString();
int score = Convert.ToInt32(reader["score"]);
}
// 關閉數據庫連接
connection.Close();
以上是一些常用的Unity數據存儲和讀取方法,具體選擇哪種方法取決于數據的復雜度和存儲需求。