您的位置:首页 > 移动开发 > Unity3D

Unity读取本地图片资源

2016-04-08 17:08 786 查看
我们以Unity读取本地图片资源为例,总结三种读取方法:

1.采用Resource.Load方法读取,读取在Unity中Assets下Resources目录下的资源名,注意不采用后缀名。(意思是Load方法直接在Resources目录下找资源,路径已经指定)。

<p><wbr>//加载图片方式1;(图片要放入在Assets/Resources/目录下); <wbr> <wbr> <wbr> <wbr> <wbr> <wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></p>Texture2D _tex = (Texture2D)Resources.Load("Lighthouse");


2.采用WWW类加载资源,此WWW类可以加载网络资源(http://格式),文件协议资源(flie://格式),ftp格式等等。

//加载图片方式2;(可以加载网络服务器和本地图片);
string filePath = "file://" + Application.dataPath +@"/_Image/grid.png";
WWW www = new WWW(filePath);
yield return www ;


3.采用C#的Image类进行图片的加载,获取Image类中的图片数据,为Unity中Texture2D的数据填充。注意此种方式可能出现的问题:

Assets/_Script/AddObjBtnEvent.cs(57,20): error CS0234: The typeor namespace name `Drawing' does not exist in the namespace`System'. Are you missing an assembly reference?

解决方法之一:
D:\ProgramFiles\Unity\Editor\Data\Mono\lib\mono\2.0\System.Drawing.dll将此路径下的System.Drawing.dll拖入到Project面板层次下,即可编译通过。

//加载图片方式3;
filePath = Application.dataPath + @"/_Image/grid.png";
FileStream fs = newFileStream(filePath,FileMode.Open,FileAccess.Read);
System.Drawing.Image img =System.Drawing.Image.FromStream(fs);
//System.Drawing.Image.FromFile(filePath); //方法二加载图片方式。

MemoryStream ms = new MemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Png);

Texture2D _tex2 = new Texture2D(128, 128);
_tex2.LoadImage(ms.ToArray());

//此处为GameObject的材质类附上读取的纹理;
_newObj.renderer.material.mainTexture = _tex2;
原文地址:http://wuzhouyi2012.blog.163.com/blog/static/204968271201301744231736
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: