文章目录
U3D 动态加载资源
1、Resource.load 加载资源
1.1、场景中添加3D模型

1.2 添加预设文件
将添加的模型文件存放到 Assets->Resources->Prefabs 目录下(没有此目录的创建目录)
 
1.3 删除场景中的模型

1.4 创建加载 模型脚本
脚本资源存放在 Assets->Script目录下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateBoxScript : MonoBehaviour
{
    GameObject boxPrefab;
    Texture tex;
    // Start is called before the first frame update
    void Start()
    {
        /// 
        boxPrefab = Resources.Load<GameObject>("Prefabs/box");
        tex = Resources.Load<Texture>("Images/aaa");
        for (int i = -2; i < 3; i++) {
            for (int j = -2; j < 3; j++)
            {
                if (Mathf.Abs(i) == 2|| Mathf.Abs(j)==2) 
                {
                    Vector3  vector3 = new Vector3(i+i*0.1f, 0, j + j * 0.1f);
                    GameObject box= Instantiate(boxPrefab, vector3, Quaternion.identity);
                    box.GetComponent<MeshRenderer>().material.mainTexture = tex;
                    box.AddComponent<Rigidbody>();         
                    
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}
1.5 将脚本挂在到 Main Camera上
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QT3yphyu-1646983115322)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216111458787.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/1cW2d95dA1.png)
1.6 运行后效果
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZTgDhach-1646983115322)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216111545842.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/300V941VOB.png)
1.7 总结
Resource.load 方式只能加载Resources目录中的资源
2、AssetBundle 加载资源
2.1 场景中添加3D模型
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oi3Jrdmt-1646983115323)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216112223606.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/A6J6J1a109.png)
2.2 创建脚本
创建模型自动旋转的脚本,分别挂载到 添加的两个模型上
一个3D模型自动旋转的脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FaceAnimation : MonoBehaviour
{
    float speed = 0.5f;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        this.transform.Rotate(Vector3.up*speed);
    }
}
2.3 添加预设文件
将animationA 添加为预设文件,删除场景中animationA 模型文件
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OehMbWks-1646983115323)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216112741734.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/0e1141I72S.png)
2.4 创建预设文件打包脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class CreateAssetBundle : MonoBehaviour
{
    public GameObject assetBundle;
    public GameObject assetBundlePrefab;
    /**
     *   选中文件 单独打包
     *  
     */
    [MenuItem("Custom Editor/CreateABMain")]
    static void CreateAssetBundleMain() {
        // 打包选中的游戏对象,获取到在 Asset 下选中的资源文件
        Object[] selectedAsset = Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
        AssetBundleBuild [] bundleMap=new AssetBundleBuild[selectedAsset.Length];   
        for (int i = 0; i < selectedAsset.Length; i++)
        {
            bundleMap[i].assetBundleName = selectedAsset[i].name;
            string sourcePath=AssetDatabase.GetAssetPath(selectedAsset[i]);
            bundleMap[i].assetNames = new string[] { sourcePath };
            if (BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath,
                
                bundleMap,
                BuildAssetBundleOptions.ForceRebuildAssetBundle,
               BuildTarget.Android
                )) 
            {
                Debug.Log("打包成功");
            }
            else
            {
                Debug.Log("打包失败");
            }
        }
        AssetDatabase.Refresh();
    }
    /**
     *   选中文件 统一打一个包
     *  
     */
    [MenuItem("Custom Editor/CreateABAll")]
    static void CreateAssetBundleAll()
    { 
    
        Caching.ClearCache();
        Object[] selectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        AssetBundleBuild[] bundleMap = new AssetBundleBuild[1];
        bundleMap[0].assetBundleName = "ALL";
        bundleMap[0].assetNames = new string[selectedAsset.Length];
        for (int i = 0; i < selectedAsset.Length; i++) 
        {
            bundleMap[0].assetNames[i]=AssetDatabase.GetAssetPath(selectedAsset[i]); 
            
        }
        if (BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath,
                bundleMap,
                BuildAssetBundleOptions.ForceRebuildAssetBundle,
                BuildTarget.Android
                ))
        {
            Debug.Log("打包成功");
        }
        else
        {
            Debug.Log("打包失败");
        }
    }
}
2.4 资源打包
Assets->StreamingAssets 打包生成文件 所在路径

点击后生成后查看 StreamingAssets 文件
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7NeAFpxf-1646983115324)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216113554715.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/aP11Q0OF1S.png)
2.5 加载打包资源
在Script 文件夹下,创建脚本DecompressScript 脚本,并且 挂载到 Main Camera 上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DecompressScript : MonoBehaviour
{
    public string pathUrl;
    // Start is called before the first frame update
    void Start()
    {
        // window 平台下的目录
        //pathUrl = "file://" + Application.streamingAssetsPath + "/";
        // android  平台下的目录
        pathUrl = "file://"+Application.persistentDataPath + "/";
        
    }
    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnGUI()
    {
        if (GUILayout.Button("Red Asset", GUILayout.Width(200), GUILayout.Height(100))) {
            Debug.Log("Application.streamingAssetsPath::::" + pathUrl + "/prefab_red");
            //StartCoroutine(LoadSingleAssetBundle(pathUrl + "prefab_red"));
            StartCoroutine(LoadSingleAssetBundle(pathUrl + "prefab_open"));
        }
        if (GUILayout.Button("Green Asset", GUILayout.Width(200), GUILayout.Height(100)))
        {
            Debug.Log("Application.streamingAssetsPath::::" + pathUrl + "/prefab_green");
           // StartCoroutine(LoadSingleAssetBundle(pathUrl + "prefab_green"));
            StartCoroutine(LoadSingleAssetBundle(pathUrl + "prefab_close"));
        }
        if (GUILayout.Button("ALL Asset", GUILayout.Width(200), GUILayout.Height(100)))
        {
            Debug.Log("Application.streamingAssetsPath::::" + pathUrl + "/all");
            //StartCoroutine(LoadAllAssetBundle(pathUrl + "all"));
            StartCoroutine(LoadAllAssetBundle(pathUrl + "all"));
        }
        // 界面上创建按钮 更新资源
        if (GUILayout.Button("Animation Asset", GUILayout.Width(200), GUILayout.Height(100)))
        {
            Debug.Log("Application.streamingAssetsPath::::" + pathUrl + "/animationA");
            //StartCoroutine(LoadSingleAssetBundle(pathUrl + "prefab_red"));
            GameObject.Find("animation_model").SetActive(false);
            StartCoroutine(LoadSingleAssetBundle(pathUrl + "animationA"));
        }
    }
    IEnumerator LoadSingleAssetBundle(string path) { 
    
        WWW bundle=new WWW(path);
        yield return bundle;
        GameObject objPrefab = bundle.assetBundle.LoadAsset(bundle.assetBundle.name)as GameObject;
        GameObject obj
            =Instantiate(objPrefab);
    }
    IEnumerator LoadAllAssetBundle(string path)
    {
        Debug.Log("加载目录 "+ path);
        WWW bundle = new WWW(path);
        yield return bundle;
        GameObject[] assets = bundle.assetBundle.LoadAllAssets<GameObject> ();
        for (int i = 0; i < assets.Length; i++)
        {
            GameObject obj
           = Instantiate(assets[i]);
            yield return obj;
        }
    }
}
2.6 运行查看效果
2.6.1替换之前的效果
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kqbzbwzo-1646983115325)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216114149434.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/09C3T1070G.png)
2.6.2替换之后的效果
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F6sMP5o1-1646983115325)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220216114304787.png)]](https://file.cfanz.cn/uploads/png/2022/03/11/23/28cEAV1a0D.png)
2.7 Android 平台上更新
2.7.1 修改 解压脚本
pathUrl = "file://"+Application.persistentDataPath + "/";
2.72 修改打包脚本
BuildTarget.Android 是android 平台
BuildTarget.StandaloneWindows 是windows平台
 if (BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath,
                bundleMap,
                BuildAssetBundleOptions.ForceRebuildAssetBundle,
                BuildTarget.Android
                ))
2.7.3 android 平台的 资源包放置路径
将打包好的资源放置到 Android/data/xxx.xx.xx/files/ 目录下
3、参考资料
视频资源:
https://www.bilibili.com/video/BV1rJ411G71R?p=1
文档资源:
https://blog.csdn.net/u010838555/article/details/71194939
https://blog.csdn.net/qq_35711014/article/details/89891139










