Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

unity使用AssetBundle.LoadFromFile(abPath)如果路径下的ab已经加载过了会报错,我该如何处理这个报错?

  1. User

    unity使用AssetBundle.LoadFromFile(abPath)如果路径下的ab已经加载过了会报错,我该如何处理这个报错?

  2. Assistant

    在调用AssetBundle.LoadFromFile(abPath)之前,可以先使用AssetBundle.LoadFromFile(abPath)检查该路径下的AssetBundle是否已经加载过了。如果已经加载过了,可以直接使用已经加载的AssetBundle,否则再调用AssetBundle.LoadFromFile(abPath)来加载。示例代码如下:

    AssetBundle ab = null;
    if (AssetBundle.allLoadedAssetBundles != null && AssetBundle.allLoadedAssetBundles.ContainsKey(abPath))
    {
        ab = AssetBundle.allLoadedAssetBundles[abPath];
    }
    else
    {
        ab = AssetBundle.LoadFromFile(abPath);
    }
    
  3. User

    AssetBundle没有allLoadedAssetBundles这个变量

  4. Assistant

    非常抱歉,我之前的回答有误,确实 allLoadedAssetBundles 不是 AssetBundle 类型的静态变量。如果你已经加载了这个 AssetBundle,再次加载同一路径下的 AssetBundle,会报错 Cannot load AssetBundle as it has already been loaded。这个问题可以通过记录已加载的 AssetBundle 的路径来避免。

    一个解决方法是使用一个字典来存储已经加载的 AssetBundle 的路径和 AssetBundle 实例之间的映射关系。当你想要加载 AssetBundle 时,首先检查字典里是否已经存储了该路径的 AssetBundle,如果已经加载过了,就直接返回字典里的实例。否则,再调用 AssetBundle.LoadFromFile 方法来创建 AssetBundle 实例并存储到字典里。

    以下是示例代码:

    private Dictionary<string, AssetBundle> loadedAssetBundles = new Dictionary<string, AssetBundle>();
    
    public AssetBundle LoadAssetBundle(string abPath)
    {
        if (loadedAssetBundles.ContainsKey(abPath))
        {
            return loadedAssetBundles[abPath];
        }
        else
        {
            AssetBundle ab = AssetBundle.LoadFromFile(abPath);
            loadedAssetBundles.Add(abPath, ab);
            return ab;
        }
    }
    

    这个方法会根据传入的 abPath 参数,检查字典里是否已经加载了该路径的 AssetBundle。如果加载过了,它会返回字典里的实例。否则,它会使用 AssetBundle.LoadFromFile 方法创建新的 AssetBundle 实例,并添加到字典里。这个方法的返回值是 AssetBundle 实例,你可以像平常一样使用该实例来获取里面的资源。