这篇文章主要介绍了unity 文件流读取图片与www读取图片的对比分析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
IO流代码:
void LoadByIO() {
float time = Time.time;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
fs.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
fs.Dispose();
fs = null;
Texture2D t = new Texture2D(1,1);
t.LoadImage(bytes);
img.texture = t;
Debug.Log("IO读取图片用时:" + (Time.time-time));
}
WWW代码:
IEnumerator LoadByWWW() {
float time = Time.time;
WWW w = new WWW("file://" + path);
yield return w;
if (string.IsNullOrEmpty(w.error) == false)
{
Debug.Log("error");
}
else {
img1.texture = w.texture;
}
Debug.Log("www读取图片用时:" + (Time.time - time));
}
结果截图:
补充:unity加载文件的方法-用加载图片举例
一、用Resources.Load()方法
1、把图片(转换或者不转换为sprite都可)放在Resources里
Texture2D imgTexture = Resources.Load("background_one") as Texture2D;
Sprite sprite = Sprite.Create(imgTexture, new Rect(0, 0, imgTexture.width, imgTexture.height), new Vector2(0.5f, 0.5f));
Image image = GetComponent<Image>();
image.sprite = sprite;
2、把图片转换成sprite,放在Resources
//Resources.Load加载图片默认的是Texture2D类型,加了typeof(Sprite)后,就是加载为sprite类型
//然后又转换为object,所以要再用as Sprite转换为Sprite,
//如果不加typeof(Sprite),它就是Texture2D转换为object,就不成强制转换为Sprite
Image image = GetComponent<Image>();
image.sprite = Resources.Load("background_one", typeof(Sprite)) as Sprite;
二、创建对应文件的public变量,然后再unity里把图片拖给变量赋值
public Sprite play;
public Sprite pause;
Image image = GetComponent<Image>();
image.sprite = play;
image.sprite = pause;
三、用WWW方式,既可以加载网络资源,也可以加载本地资源
//用www方式读取
string path = @"E:\UnityProject\ARVR\Workspace\Test2\Assets\texture\background_one.png";
WWW www = new WWW(path);
Texture2D texture = www.texture;
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
Image image = GetComponent<Image>();
image.sprite = sprite;
注意:用www加载,最好使用协程,等待图片加载完毕
四、用传统IO流
//创建文件读取流
string path = @"E:\UnityProject\ARVR\Workspace\Test2\Assets\texture\background_one.png";
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
byte[] bye = new byte[fileStream.Length];
fileStream.Read(bye, 0, bye.Length);
fileStream.Close();
//创建texture
Texture2D texture2D = new Texture2D(240, 144);
texture2D.LoadImage(bye);
//创建sprite
Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f));
Image image = GetComponent<Image>();
image.sprite = sprite;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持得得之家。如有错误或未考虑完全的地方,望不吝赐教。
沃梦达教程
本文标题为:unity 文件流读取图片与www读取图片的区别介绍
基础教程推荐
猜你喜欢
- C#控制台实现飞行棋小游戏 2023-04-22
- ZooKeeper的安装及部署教程 2023-01-22
- C# windows语音识别与朗读实例 2023-04-27
- C# 调用WebService的方法 2023-03-09
- winform把Office转成PDF文件 2023-06-14
- 一个读写csv文件的C#类 2022-11-06
- C#类和结构详解 2023-05-30
- unity实现动态排行榜 2023-04-27
- C# List实现行转列的通用方案 2022-11-02
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26