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

Unity安卓构建中TensorFlow Lite模型出现NullReferenceException求助

解决Unity中TensorFlow Lite Interpreter初始化的NullReferenceException

可能原因及排查步骤

  • 原生库未正确加载
    这个错误大概率是TFLite的底层原生库(Android的.so、iOS的.framework或Windows的.dll)未正确导入或加载。检查插件包内Plugins目录,确认对应你当前开发平台(如Windows/x86_64、Android/armeabi-v7a等)的原生库文件存在,且在Unity Inspector中设置了正确的平台兼容选项(比如Android平台需勾选对应CPU架构)。

  • 模型格式/版本不兼容
    确认你的TFLite模型是用兼容版本的TensorFlow导出的(比如插件基于TF 2.x时,模型不能是TF 1.x的旧格式)。可先用Python的tflite.Interpreter加载模型验证有效性,命令示例:

    import tensorflow as tf
    interpreter = tf.lite.Interpreter(model_path="your_model.tflite")
    interpreter.allocate_tensors()
    

    如果Python中能正常初始化,说明模型本身没问题,问题出在Unity端的插件适配。

  • 脚本执行顺序冲突
    检查ListenerController的执行顺序是否早于TFLite插件的初始化逻辑。在Edit > Project Settings > Script Execution Order中调整顺序,让TFLite相关初始化代码优先执行。

  • 插件与Unity版本不兼容
    确认com.github.asus4.tflite插件版本和当前Unity版本匹配。部分旧版本插件可能不支持Unity 2022+的新特性,或新版本插件移除了旧API,可尝试切换到插件的稳定发行版本。

代码层面的强校验建议

即使你认为模型读取正常,也可以在初始化前添加强校验逻辑,确保数据无误:

void Start()
{
    TextAsset modelAsset = Resources.Load<TextAsset>("your_model");
    if (modelAsset == null)
    {
        Debug.LogError("模型资源未找到,请检查Resources目录下的模型文件");
        return;
    }
    byte[] modelData = modelAsset.bytes;
    if (modelData == null || modelData.Length == 0)
    {
        Debug.LogError("读取到的模型数据为空");
        return;
    }
    try
    {
        var interpreter = new TensorFlowLite.Interpreter(modelData);
        // 后续模型初始化逻辑
    }
    catch (Exception e)
    {
        Debug.LogError($"Interpreter初始化失败: {e.Message}\n{e.StackTrace}");
    }
}

额外排查点

  • 检查Unity Player Settings,比如Android平台是否启用IL2CPP后端,部分TFLite插件在Mono后端下存在兼容性问题。
  • 删除Unity项目的Library目录清理缓存,重新导入插件,避免缓存导致的资源加载异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:52:37