封装加载资源的方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_44238513/article/details/90704645
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ResLoad : MonoBehaviour {

    public static string dir;
    public static string dir02;

    void Awake()
    {
        dir = Application.dataPath + "/StreamingAssets/Windows/Windows";
        dir02 = Application.dataPath + "/StreamingAssets/Windows";
        //加载资源之前要把依赖的资源全部加载进来
        GameObject player = LoadAssetByName("", "models.u3d", "player") as GameObject;
        Instantiate(player).transform.position = Vector3.zero;
    }

    // Use this for initialization
    void Start()
    {

    }
	
    /// <summary>
    /// 封装加载资源的方法
    /// </summary>
    /// <param name="AssetBundleName"></param>
    /// <param name="resName"></param>
    /// <returns></returns>
    public static Object LoadAssetByName(string forderName,string AssetBundleName,string resName)
    {
        //加载总的资源
        AssetBundle assetBundle = AssetBundle.LoadFromFile(dir);
        // 从总资源中总的依赖文件列表
        AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        //根据需要加载的资源包名称  读取出来这个资源包依赖的所有资源包的名称
        string[] dependencies = manifest.GetAllDependencies(AssetBundleName);
        //通过循环把依赖的资源包全部先加载一遍
        foreach (var dependency in dependencies)
        {
            Debug.Log("依赖的资源包名称:" + dependency);
            //通过循环把依赖的资源包全部先加载一遍
            AssetBundle.LoadFromFile(dir02 + "/" + dependency);
        }
        //最后加载我们需要的资源包
        AssetBundle ab = AssetBundle.LoadFromFile(dir02+forderName+"/"+AssetBundleName);
        //从assetBundle中读取我们需要的资源
        GameObject prefab = ab.LoadAsset(resName) as GameObject;
        return prefab;
        //Instantiate(prefab).transform.position = Vector3.zero;
    }
    // Update is called once per frame
    void Update () {
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_44238513/article/details/90704645