当前位置:网站首页>Unitywebrequest is used in unity to load network and local pictures
Unitywebrequest is used in unity to load network and local pictures
2022-07-28 11:57:00 【Walking on the top of the clouds】
In the actual project , There are often some needs to load pictures from the network to show . For example, players' avatars , Announcement big picture and some display pictures that need to be loaded , At this time, you need to use code to load the necessary image resources from the network .
Update the iterative version Unity Has been gradually giving up on WWW Support for , Introduction UnityWebRequest, See Unity Resource storage and loading - Local resources Update resources .
UnityWebRequest It also supports AssetsBundle,xml Wait for the download of file resources .
This paper is based on UnityWebRequest On the basis of , Realize the loading of network pictures and local disk pictures , And implemented on the screen .
First look at the use of WWW How to complete the image loading :
using (WWW www = new WWW(url))
{
yield return www;
if (string.IsNullOrEmpty(www.error))
{
// Get the picture in the link
Texture2D texture = www.texture;
}
}This code is relatively simple , Back to www.texture Is the link image , This completes the simple image loading .
however , actually , Usually, you need to load pictures into memory and cache them locally , So that it can be loaded quickly next time , Instead of pulling from the network again .
technological process :

Key code :github Address
///LoadImageMgr.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using UnityEngine.Networking;
public class LoadImageMgr
{
/// <summary>
/// download from web or hard disk
/// </summary>
/// <param name="url"></param>
/// <param name="loadEnd">callback</param>
/// <returns></returns>
public IEnumerator LoadImage(string url, Action<Texture2D> loadEnd)
{
Texture2D texture = null;
// Load from memory first
if (imageDic.TryGetValue(url,out texture))
{
loadEnd.Invoke(texture);
yield break;
}
string savePath = GetLocalPath();
string filePath = string.Format("file://{0}/{1}.png", savePath, UnityUtil.MD5Encrypt(url));
//from hard disk
bool hasLoad = false;
if (Directory.Exists(filePath))
yield return DownloadImage(filePath, (state, localTexture) =>
{
hasLoad = state;
if (state)
{
loadEnd.Invoke(localTexture);
if (!imageDic.ContainsKey(url))
imageDic.Add(url, localTexture);
}
});
if (hasLoad) yield break; //loaded
//from web
yield return DownloadImage(url, (state, downloadTexture) =>
{
hasLoad = state;
if (state)
{
loadEnd.Invoke(downloadTexture);
if (!imageDic.ContainsKey(url))
imageDic.Add(url, downloadTexture);
Save2LocalPath(url, downloadTexture);
}
});
}
public IEnumerator DownloadImage(string url, Action<bool, Texture2D> downloadEnd)
{
using (UnityWebRequest request = new UnityWebRequest(url))
{
DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
request.downloadHandler = downloadHandlerTexture;
yield return request.Send();
if (string.IsNullOrEmpty(request.error))
{
Texture2D localTexture = downloadHandlerTexture.texture;
downloadEnd.Invoke(true, localTexture);
}
else
{
downloadEnd.Invoke(false, null);
Debug.Log(request.error);
}
}
}
/// <summary>
/// save the picture
/// </summary>
/// <param name="url"></param>
/// <param name="texture"></param>
private void Save2LocalPath(string url, Texture2D texture)
{
byte[] bytes = texture.EncodeToPNG();
string savePath = GetLocalPath();
try
{
File.WriteAllBytes( string.Format("{0}/{1}.png", savePath , UnityUtil.MD5Encrypt(url)), bytes);
}
catch(Exception ex)
{
Debug.LogError(ex.ToString());
}
}
/// <summary>
/// get which path will save
/// </summary>
/// <returns></returns>
private string GetLocalPath()
{
string savePath = Application.persistentDataPath + "/pics";
#if UNITY_EDITOR
savePath = Application.dataPath + "/pics";
#endif
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
return savePath;
}
private Dictionary<string, Texture2D> imageDic = new Dictionary<string, Texture2D>();
public static LoadImageMgr instance { get; private set; } = new LoadImageMgr();
}
///LoadImageHelper.cs
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LoadImageHelper : MonoBehaviour
{
string defaultUrl = "http://avatar.csdnimg.cn/1/E/6/2_u013012420.jpg";
/// <summary>
/// use this to load image
/// </summary>
/// <param name="texture"></param>
/// <param name="url"></param>
public void LoadImage(RawImage rawImage, string url)
{
if (string.IsNullOrEmpty(url))
{
url = defaultUrl;
}
StartCoroutine(LoadTeture(url, (tex) => {
rawImage.texture = tex;
}));
}
IEnumerator LoadTeture(string url, Action<Texture2D> cb)
{
yield return LoadImageMgr.instance.LoadImage(url, cb);
}
}
边栏推荐
- Update dev (development version) of the latest win11
- How to make the characters in the photos laugh? HMS core video editing service one click smile function makes people smile more naturally
- An example of the mandatory measures of Microsoft edge browser tracking prevention
- Six papers that must be seen in the field of target detection
- Software testing and quality learning notes 1 --- black box testing
- Three methods of using unity mouse to drive objects
- Are interviews all about memorizing answers?
- R language ggplot2 visualization: ggdensity function of ggpubr package visualizes density graph and uses stat_ overlay_ normal_ Density function superimposes positive distribution curve, custom config
- How async await implements concurrency
- Untiy中控制Animation的播放速度
猜你喜欢

Consumer installation and configuration

consul安装与配置

Unity中使用UnityWebRequest进行网络和本地图片加载

Today's sleep quality record 74 points

Hcip day 6 (OSPF related knowledge)

Design a system that supports millions of users

瑞吉外卖——Day01

15、用户web层服务(三)
![[general database integrated development environment] Shanghai daoning provides you with Aqua Data Studio downloads, tutorials, and trials](/img/46/830b7703ae7cbfa6051137061560c2.png)
[general database integrated development environment] Shanghai daoning provides you with Aqua Data Studio downloads, tutorials, and trials

Service Workers让网站动态加载Webp图片
随机推荐
强缓存、协商缓存具体过程
301. Delete invalid brackets
Advanced database technology learning notes 1 -- Oracle deployment and pl/sql overview
Summary of common RSA related problems in CTF: basic RSA encryption and decryption
R language - some metrics for unbalanced data sets
Autumn recruit offer harvesters, and take the offers of major manufacturers at will
Learn to use MySQL explain to execute the plan, and SQL performance tuning is no longer difficult
15. User web layer services (III)
How to effectively implement a rapid and reasonable safety evacuation system in hospitals
Skiasharp's WPF self drawn drag ball (case version)
Database advanced learning notes - storage structure
boost官网搜索引擎项目详解
Reflect 机制获取Class 的属性和方法信息
从零开始Blazor Server(2)--整合数据库
Why does acid food hurt teeth + early periodontitis
Three methods of using unity mouse to drive objects
LabVIEW AI视觉工具包(非NI Vision)下载与安装教程
Application of mobile face stylization Technology
Interfaces and abstract classes
Database advanced learning notes - system package