当前位置:网站首页>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);
}
}
边栏推荐
- [pyGame practice] the super interesting bubble game is coming - may you be childlike and always happy and simple~
- Leecode8 string conversion integer (ATOI)
- Lua 中 __index、__newindex、rawget、rawset的理解
- Interfaces and abstract classes
- Advanced database technology learning notes 1 -- Oracle deployment and pl/sql overview
- Globalthis is not defined solution
- Several reincarnation stories
- [pyGame practice] when the end of the world comes, how long can you live in a cruel survival game that really starts from scratch?
- Hcip day 6 (OSPF related knowledge)
- Unity中使用UnityWebRequest进行网络和本地图片加载
猜你喜欢

consul安装与配置

Autumn recruit offer harvesters, and take the offers of major manufacturers at will

Three methods of using unity mouse to drive objects

Direct insert sort and Hill sort

Software testing and quality learning notes 1 --- black box testing

Cvpr2020 best paper: unsupervised learning of symmetric deformable 3D objects

Know the optical fiber interface and supporting optical fiber cable of can optical fiber converter in fire alarm networking
![ASP. Net core 6 framework unveiling example demonstration [29]: building a file server](/img/90/40869d7c03f09010beb989af07e2f0.png)
ASP. Net core 6 framework unveiling example demonstration [29]: building a file server

boost官网搜索引擎项目详解

Modify the running container port mapping
随机推荐
R language ggplot2 visualization: use the ggboxplot function of ggpubr package to visualize the box diagram and customize the fill parameter to configure the filling color of the box
Shell (II)
Upgrading of computing power under the coordination of software and hardware, redefining productivity
可视化大型时间序列的技巧。
Will PFP be the future of digital collections?
Lua对table进行深拷贝
[diary of supplementary questions] [2022 Niuke summer multi school 2] l-link with level editor I
In order to ensure the normal operation of fire-fighting equipment in large buildings, the power supply monitoring system of fire-fighting equipment plays a key role
[diary of supplementary questions] [2022 Niuke summer multi school 2] D-Link with game glitch
Five Ali technical experts have been offered. How many interview questions can you answer
Database advanced learning notes - storage structure
Docker runs MySQL service
Database advanced learning notes -- object type
Embrace open source guidelines
PFP会是数字藏品的未来吗?
How to make the characters in the photos laugh? HMS core video editing service one click smile function makes people smile more naturally
R language uses dplyr package group_ By function and summarize function calculate the mean value of all covariates involved in the analysis based on grouped variables (difference in means of covariate
WPF layout controls are scaled up and down with the window, which is suitable for multi-resolution full screen filling applications
Byte side: how to realize reliable transmission with UDP?
Static proxy instance