Assetbundle之 资源加载的三种方法

首先创建Editor文件夹,在此文件夹下创建Create Asset bundle脚本文件对资源进行打包,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class CreateAssetbundles
{
    [MenuItem("Assetbundles/BuildAssetBundles")]
    static void BuildAssetbundles()
    {
        string streamPath = Application.streamingAssetsPath;
        if (!Directory.Exists(streamPath))
        {
            Directory.CreateDirectory(streamPath);
        }
        BuildPipeline.BuildAssetBundles(streamPath,BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows);
    }
}

Assetbundle之 资源加载的三种方法_第1张图片

接下来介绍加载资源的四三方法:创建Load from file脚本文件,:

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class Loadfromfile : MonoBehaviour {
    private void Start()
    {
        //LoadPrefabs();
       // LoadPrefabs2();
        LoadPrefabs3();
    }
    void LoadPrefabs()//第一种从内存中加载
    {
        string path = Application.streamingAssetsPath + "/player.unity3d";
        //  File.ReadAllBytes(path) 是把本地资源加到内存中去
        //LoadFromMemory 再从内存中加载 
        AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));
        Object[] obj = ab.LoadAllAssets();
        foreach (var o in obj)
        {
            Instantiate(o);
        }
    }
    void LoadPrefabs2()//第二种直接从本地加载
    {
        string path = Application.streamingAssetsPath + "/player.unity3d";
        AssetBundle ab = AssetBundle.LoadFromFile((path));
        Object[] obj = ab.LoadAllAssets();
        foreach (var o in obj)
        {
            Instantiate(o);
        }
    }
    void LoadPrefabs3()//第三种利用www从本地加载
    {
        string path ="file://"+ Application.streamingAssetsPath + "/player.unity3d";
        WWW www= WWW.LoadFromCacheOrDownload(path,1);
        AssetBundle ab = www.assetBundle;
        Object[] obj = ab.LoadAllAssets();
        foreach (var o in obj)
        {
            Instantiate(o);
        }
    }
}

每个方法结果是相同的:

Assetbundle之 资源加载的三种方法_第2张图片

下一节介绍加载资源之间的依赖关系

相关知识借鉴:https://www.bilibili.com/video/av40307996?from=search&seid=2999299457993702151

 

你可能感兴趣的:(Unity日常小结)