Unity 好友列表、聊天记录使用本地数据库储存 --SimpleSQL SQLite
using SimpleSQL;
// 初始化数据库
SQLite db = new SQLite(Application.persistentDataPath + "/FriendList.db");
// 创建好友列表表格
db.CreateTable("CREATE TABLE IF NOT EXISTS FriendList (id INTEGER PRIMARY KEY, name TEXT, status TEXT, timestamp TEXT)");
// 添加好友到列表
public void AddFriend(string name, string status)
{
db.Insert("INSERT INTO FriendList (name, status) VALUES (?, ?)", name, status);
}
// 获取好友列表
public List<Friend> GetFriendList()
{
List<Friend> friendList = new List<Friend>();
SQLiteRows rows = db.GetRows("SELECT * FROM FriendList");
foreach (SQLiteRow row in rows)
{
friendList.Add(new Friend(row["id"], row["name"], row["status"], row["timestamp"]));
}
return friendList;
}
// 删除好友
public void DeleteFriend(int id)
{
db.Execute("DELETE FROM FriendList WHERE id = ?", id);
}
// 聊天记录表格
db.CreateTable("CREATE TABLE IF NOT EXISTS ChatHistory (id INTEGER PRIMARY KEY, sender TEXT, receiver TEXT, message TEXT, timestamp TEXT)");
// 添加聊天记录
public void AddChatRecord(string sender, string receiver, string message)
{
db.Insert("INSERT INTO ChatHistory (sender, receiver, message) VALUES (?, ?, ?)", sender, receiver, message);
}
// 获取聊天记录
public List<ChatRecord> GetChatHistory(string sender, string receiver)
{
List<ChatRecord> chatHistory = new List<ChatRecord>();
SQLiteRows rows = db.GetRows("SELECT * FROM ChatHistory WHERE sender = ? AND receiver = ?", sender, receiver);
foreach (SQLiteRow row in rows)
{
chatHistory.Add(new ChatRecord(row["id"], row["sender"], row["receiver"], row["message"], row["timestamp"]));
}
return chatHistory;
}
这个代码示例展示了如何使用SimpleSQL SQLite库来管理Unity游戏中的好友列表和聊天记录。它包括了创建数据库表格、添加数据、查询数据以及删除数据的基本操作。这些操作是保存和检索用户数据的理想选择,尤其是对于需要离线模式的游戏。
评论已关闭