You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中SQLite背包数据Getter报错NullReferenceException无法读取数据

问题核心原因

你遇到的NullReferenceException错误核心原因是当SQL查询没有匹配到对应ID的Inventory记录时,inventorySave变量没有被初始化:

  • 你调用GetInventoryByID(0)时,查询的是ID为0的记录,如果数据库里这条记录不存在,reader.Read()会返回false,while循环全程不会执行,inventorySave就还是默认的null值
  • 后续你直接访问inventorySave.Potion_Small等属性、调用inventorySave.ReturnInventoryData()就会触发空引用异常

修复方案

1. 新增非空校验,避免空引用崩溃

在读取完数据库后先判断inventorySave是否为空,为空的话走默认初始化逻辑即可,同时建议优化SQL写法避免注入风险:

public int[] GetInventoryByID(int ID)
{
    // 建议将inventorySave声明在方法内部,避免全局变量污染
    InventoryEntity inventorySave = null;
    using(var connection = new SqliteConnection(DB_Name))
    {
        connection.Open();
        using(var command = connection.CreateCommand())
        {
            // 改成参数化查询,避免SQL注入风险,也减少SQL语法错误概率
            command.CommandText = "SELECT * FROM Inventory WHERE ID = @ID;";
            command.Parameters.AddWithValue("@ID", ID);
            using(IDataReader reader = command.ExecuteReader())
            {
                // ID是主键的话最多只会有一条记录,用if代替while更合理
                if (reader.Read())
                {
                    Debug.Log("InventoryEntity");
                    inventorySave = new InventoryEntity(
                        int.Parse(reader[0].ToString()),
                        int.Parse(reader[1].ToString()),
                        int.Parse(reader[2].ToString()),
                        int.Parse(reader[3].ToString()),
                        int.Parse(reader[4].ToString()),
                        int.Parse(reader[5].ToString()),
                        int.Parse(reader[6].ToString())
                    );
                    Debug.Log("Invetory potion Small" + inventorySave.Potion_Small);
                }
                reader.Close();
            }
        }
        connection.Close();
    }
    // 新增非空判断逻辑
    if(inventorySave == null)
    {
        Debug.LogError($"未查询到ID为{ID}的背包数据,将初始化默认空背包");
        // 按你的InventoryEntity构造函数参数顺序传入默认值即可
        inventorySave = new InventoryEntity(ID,0,0,0,0,0,0);
    }
    Debug.Log("Inventory :" +"\n"
    + "Potion_Small :" + inventorySave.Potion_Small +"\n" 
    + "Potion_Middle :" +inventorySave.Potion_Middle +"\n"
    + "Potion_Grand :" +inventorySave.Potion_Grand + "\n"
    + "Pokeball :" +inventorySave.Pokeball + "\n"
    + "Superball :" +inventorySave.Superball + "\n"
    + "Ultraball :" +inventorySave.Ultraball);
    return inventorySave.ReturnInventoryData();
}

2. 排查数据库数据异常

如果确认已经写入过ID为0的记录还是查不到,按如下步骤排查:

  • 确认数据库连接字符串DB_Name指向的是你写入数据的同一个数据库文件,Unity环境下注意不要指向了StreamingAssets里的只读模板库,要指向可读写的Application.persistentDataPath目录下的数据库
  • 直接打开数据库文件查看Inventory表是否真的存在ID=0的记录,同时确认字段顺序和你读取的索引顺序一致,避免字段错位
  • SQLite的ID字段如果是自增主键,第一条记录默认ID为1而不是0,如果你写数据时没有手动指定ID=0,查询ID=0自然返回空结果

内容的提问来源于stack exchange,提问作者Grilya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 06:42:01