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);
    }
}

接下来介绍加载资源的四三方法:创建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<GameObject>();
        foreach (var o in obj)
        {
            Instantiate(o);
        }
    }
    void LoadPrefabs2()//第二种直接从本地加载
    {
        string path = Application.streamingAssetsPath + "/player.unity3d";
        AssetBundle ab = AssetBundle.LoadFromFile((path));
        Object[] obj = ab.LoadAllAssets<GameObject>();
        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<GameObject>();
        foreach (var o in obj)
        {
            Instantiate(o);
        }
    }
}

每个方法结果是相同的:

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

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

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值