Unity 出现error CS0103: The name ‘AssetDatabase‘ does not exist in the current context

这篇具有很好参考价值的文章主要介绍了Unity 出现error CS0103: The name ‘AssetDatabase‘ does not exist in the current context。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

问题描述

在Unity场景中,在进行build操作时出现这种报错,导致资源bundle无法正常生成,出现以下问题:

error CS0103: The name 'AssetDatabase' does not exist in the current context

error CS0234: The type or namespace name 'AssetDatabase' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

ps:上面两种错误都是同一种问题造成的,报错不一样的原因是由于UnityEditor在代码中的位置不同造成的:
前者是在开头声明了using UnityEditor,方法中使用AssetDatabase.LoadAssetAtPath;
后者是未声明using UnityEditor,而是在方法中直接使用了UnityEditor.AssetDatabase.LoadAssetAtPath


原因分析

在非Editor文件夹下的脚本中,存在着有关UnityEditor方法的使用

方法中第一行使用了UnityEditor中的AssetDatabase.LoadAssetAtPath方法,并且该方法所在的文件并非是在Editor文件夹下,导致build操作时出现报错

    private void EditorLoadAsset(string assetName, Action<UnityEngine.Object> action)
    {
        UnityEngine.Object obj = UnityEditor.AssetDatabase.LoadAssetAtPath(assetName, typeof(UObject));
        if (obj == null)
            Debug.LogError("asset name is not exist: " + assetName);
        action?.Invoke(obj);
    }

Unity 出现error CS0103: The name ‘AssetDatabase‘ does not exist in the current context


解决方案

添加
#if UNITY_EDITOR

#endif

在方法外部,加上#if UNITY_EDITOR #endif,保证该方法只有在Unity编辑器中运行

#if UNITY_EDITOR
    private void EditorLoadAsset(string assetName, Action<UnityEngine.Object> action)
    {
        UnityEngine.Object obj = UnityEditor.AssetDatabase.LoadAssetAtPath(assetName, typeof(UObject));
        if (obj == null)
            Debug.LogError("asset name is not exist: " + assetName);
        action?.Invoke(obj);
    }
#endif

注意

注:需要把调用该方法的地方也要用#if #endif包括起来
因为该方法时需要被调用的,然后测试的时候出现了以下问题
error CS0103: The name 'EditorLoadAsset' does not exist in the current context
出现问题的原因是调用此方法的地方未用#if #endif包含进去,在正式运行状态下,他会认为该方法不存在,找不到该方法导出出现报错。所以要将调用该方法的地方也要用#if #endif包括进来,让正式运行状态下也不用执行调用该方法的语句文章来源地址https://www.toymoban.com/news/detail-405726.html

到了这里,关于Unity 出现error CS0103: The name ‘AssetDatabase‘ does not exist in the current context的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包