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数据存储和读取方法,具体选择哪种方法取决于数据的复杂度和存储需求。