問(wèn)題描述
在Unity場(chǎng)景中,在進(jìn)行build操作時(shí)出現(xiàn)這種報(bào)錯(cuò),導(dǎo)致資源bundle無(wú)法正常生成,出現(xiàn)以下問(wèn)題:
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:上面兩種錯(cuò)誤都是同一種問(wèn)題造成的,報(bào)錯(cuò)不一樣的原因是由于UnityEditor在代碼中的位置不同造成的:
前者是在開(kāi)頭聲明了using UnityEditor,方法中使用AssetDatabase.LoadAssetAtPath;
后者是未聲明using UnityEditor,而是在方法中直接使用了UnityEditor.AssetDatabase.LoadAssetAtPath
原因分析
在非Editor文件夾下的腳本中,存在著有關(guān)UnityEditor方法的使用
方法中第一行使用了UnityEditor中的AssetDatabase.LoadAssetAtPath方法,并且該方法所在的文件并非是在Editor文件夾下,導(dǎo)致build操作時(shí)出現(xiàn)報(bào)錯(cuò)
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);
}
解決方案
添加
#if UNITY_EDITOR
…
#endif
在方法外部,加上#if UNITY_EDITOR #endif,保證該方法只有在Unity編輯器中運(yùn)行文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-405726.html
#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
注意
注:需要把調(diào)用該方法的地方也要用#if #endif包括起來(lái)
因?yàn)樵摲椒〞r(shí)需要被調(diào)用的,然后測(cè)試的時(shí)候出現(xiàn)了以下問(wèn)題 error CS0103: The name 'EditorLoadAsset' does not exist in the current context
出現(xiàn)問(wèn)題的原因是調(diào)用此方法的地方未用#if #endif包含進(jìn)去,在正式運(yùn)行狀態(tài)下,他會(huì)認(rèn)為該方法不存在,找不到該方法導(dǎo)出出現(xiàn)報(bào)錯(cuò)。所以要將調(diào)用該方法的地方也要用#if #endif包括進(jìn)來(lái),讓正式運(yùn)行狀態(tài)下也不用執(zhí)行調(diào)用該方法的語(yǔ)句文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-405726.html
到了這里,關(guān)于Unity 出現(xiàn)error CS0103: The name ‘AssetDatabase‘ does not exist in the current context的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!