当前位置:网站首页>Unity loads AssetBundle resources from the server and writes them to local memory, and loads the downloaded and saved AB resources from local memory to the scene
Unity loads AssetBundle resources from the server and writes them to local memory, and loads the downloaded and saved AB resources from local memory to the scene
2022-06-28 09:48:00 【John lone】
Load resources from the server :
AB After the resource is packaged, there is a 【 Directory file 】AssetBundle, He kept all AB The path and name of the resource ,
adopt aLLAssetBundleURL Link path Assembly from 【 Directory file 】 To obtain the AB The name of the resource , Then write the relevant code in the coordination method , So as to realize the function of loading resources from the server . See the code for details .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
public class DownLoadAssetBundle : MonoBehaviour
{
//AB Where the resource file is saved in the server ( My server sent , Unable to load )
private string mainAssetBundleURL = @"http://120.24.90.173/Luademo/AssetBundles/AssetBundles";
private string aLLAssetBundleURL = @"http://120.24.90.173/Luademo/AssetBundles/";
void Start()
{
StartCoroutine("DownLoadMainAssetBundle");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
LoadAssetBundle();
}
}
/// <summary>
/// Download master [ Catalog ]AssetBundle file
/// </summary>
IEnumerator DownLoadMainAssetBundle()
{
// Create a get AssetBundle Of documents web request .
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(mainAssetBundleURL);
// Send this web request .
yield return request.SendWebRequest();
// from web Get content from request , Will return a AssetBundle Data of type .
AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
if (ab == null)
{
Debug.Log("not ab");
}
// From this “ Directory file AssetBundle” In order to get manifest data .
AssetBundleManifest manifest = ab.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
// Access to this manifest All of the AssetBundle Name information of .
string[] names = manifest.GetAllAssetBundles();
for (int i = 0; i < names.Length; i++)
{
// Group spell out the download path link .
Debug.Log(aLLAssetBundleURL + names[i]);
// Download single AssetBundle Load the file into the scene .
//StartCoroutine(DownLoadSingleAssetBundle(aLLAssetBundleURL + names[i]));
// download AssetBundle And save to local .
StartCoroutine(DownLoadAssetBundleAndSave(aLLAssetBundleURL + names[i]));
}
}
/// <summary>
/// Download single AssetBundle Load the file into the scene
/// </summary>
IEnumerator DownLoadSingleAssetBundle(string url)
{
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url);
yield return request.SendWebRequest();
AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
// By getting AssetBundle Object to get the names of all internal resources ( route ), Returns an array .
string[] names = ab.GetAllAssetNames();
for (int i = 0; i < names.Length; i++)
{
//Debug.Log(names[i]);
// Intercept the file name in the path address , And no suffix . Need to introduce System.IO Namespace .
string tempName = Path.GetFileNameWithoutExtension(names[i]);
Debug.Log(tempName);
// Instantiation .
GameObject obj = ab.LoadAsset<GameObject>(tempName);
GameObject.Instantiate<GameObject>(obj);
}
}
/// <summary>
/// download AssetBundle And save to local
/// </summary>
IEnumerator DownLoadAssetBundleAndSave(string url)
{
//UnityWebRequestAssetBundle.GetAssetBundle(string uri) Use this API The downloaded resource does not support original data access .
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
// Indicates whether the download status is complete .
if (request.isDone)
{
// Use IO Technology puts this request Objects are stored locally .( Suffix required )
//SaveAssetBundle(Path.GetFileName(url), request.downloadHandler.data, request.downloadHandler.data.Length);
SaveAssetBundle2(Path.GetFileName(url), request);
}
}
/// <summary>
/// Method 1
/// Storage AssetBundle For local files
/// </summary>
private void SaveAssetBundle(string fileName, byte[] bytes, int count)
{
// Create a file information object .
FileInfo fileInfo = new FileInfo(Application.streamingAssetsPath + "//" + fileName);
// Through the file information object “ establish ” Method , Get a file stream object .
FileStream fs = fileInfo.Create();
// Through file stream objects , Write information to this file .
//fs.Write( Byte array , Starting position , Data length );
fs.Write(bytes, 0, count);
// The file is written and stored on the hard disk , Close the file stream object , Destroy the object of the document .
fs.Flush();
fs.Close();
fs.Dispose();
Debug.Log(fileName + " The download ");
}
/// <summary>
/// Method 2
/// Storage AssetBundle For local files
/// </summary>
private void SaveAssetBundle2(string fileName, UnityWebRequest request)
{
// Construct file stream .
FileStream fs = File.Create(Application.streamingAssetsPath + "//" + fileName);
// Write byte stream to file ,request.downloadHandler.data You can get the byte stream of the download resource .
fs.Write(request.downloadHandler.data, 0, request.downloadHandler.data.Length);
// The file is written and stored on the hard disk , Close the file stream object , Destroy the object of the document .
fs.Flush();
fs.Close();
fs.Dispose();
Debug.Log(fileName + " The download ");
}
/// <summary>
/// Load from local AB Resources and instantiate
/// </summary>
private void LoadAssetBundle()
{
// Load from local AB Resources to memory .
AssetBundle assetBundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/player1.ab");
// from AB Get resources from resources .
GameObject player = assetBundle.LoadAsset<GameObject>("Necromancer");
GameObject.Instantiate<GameObject>(player, Vector3.zero, Quaternion.identity);
}
}
边栏推荐
猜你喜欢

线程的生命周期

Automatic conversion - interview questions

HDI的盲孔设计,你注意到这个细节了吗?

Starting from full power to accelerate brand renewal, Chang'an electric and electrification products sound the "assembly number"

Thread lifecycle

Explain final, finally, and finalize

The concept of "tree structure" perfectly interprets the primary and secondary of things

桥接模式(Bridge)

虚拟机14安装win7(图教程)

缓存之王Caffeine Cache,性能比Guava更强
随机推荐
Comprehensive evaluation of outline note taking software workflow: advantages, disadvantages and evaluation
JVM family (2) - garbage collection
P2394 yyy loves Chemistry I
==和eqauls()的区别
DBeaver安装与使用教程(超详细安装与使用教程)
P2394 yyy loves Chemistry I
【云驻共创】DWS告警服务DMS详细介绍和集群连接方式简介
代理模式(Proxy)
This article explains in detail the difficult problems and solutions faced by 3D cameras
104. maximum depth of binary tree
Data visualization makes correlation analysis easier to use
June 27, 2022: give a 01 string with a length of N. now please find two intervals so that the number of 1 is equal and the number of 0 is equal in the two intervals. The two intervals can intersect bu
栈的弹出压入序列<难度系数>
Sword finger offer | Fibonacci sequence
当面试官让你用两种方式写BinarySort
手机号、邮箱正则验证[通俗易懂]
PMP考试重点总结七——监控过程组(1)
标识符的命名规则和规范
通过PyTorch构建的LeNet-5网络对手写数字进行训练和识别
[ybtoj advanced training guide] maximum separation [hash] [Floyd]