当前位置:网站首页>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);
}
}
边栏推荐
- PHP curl forged IP address and header information code instance - Alibaba cloud
- 线程和进程
- PMP考试重点总结四——规划过程组(2)
- 分而治之之经典Hanoi
- Bridge mode
- RESTful风格
- Custom exception classes and exercises
- Data visualization makes correlation analysis easier to use
- Differences between task parameter types inout and ref
- PMP examination key summary VIII - monitoring process group (2)
猜你喜欢

缓存之王Caffeine Cache,性能比Guava更强

1181:整数奇偶排序

Matplotlib属性及注解

Automatic conversion - interview questions

Full link service tracking implementation scheme
![[ybtoj advanced training guidance] class roll call [string hash]](/img/5b/bbf8fa51d180b50fbbee4bcc278c70.jpg)
[ybtoj advanced training guidance] class roll call [string hash]

1182: group photo effect

装饰模式(Decorator)
![[happy Lantern Festival] guessing lantern riddles eating lantern festival full of vitality ~ (with lantern riddle guessing games)](/img/04/454bede0944f56ba69cddf6b237392.jpg)
[happy Lantern Festival] guessing lantern riddles eating lantern festival full of vitality ~ (with lantern riddle guessing games)

English translation plug-in installation of idea
随机推荐
异常处理4种方法
Comprehensive evaluation of outline note taking software workflow: advantages, disadvantages and evaluation
数字人行业爆发在即,市场格局几何?
ffmpeg录音录像
当面试官让你用两种方式写BinarySort
Differences between task parameter types inout and ref
The digital human industry is about to break out. What is the market pattern?
自定义异常类及练习
MySQL的开发环境和测试环境有什么区别??
在本类私有属性直接使用?new()在使用!!!
JSON数据与List集合之间的正确转换
Prototype chain JS
On the influence of small program on the digitalization of media industry
Bridge mode
Multithreading concurrent parallel threaded process
虚拟机14安装win7(图教程)
Thread lifecycle
Dbeaver连接人大金仓KingbaseES V8(超详细图文教程)
Bron filter Course Research Report
1181: integer parity sort