Unity 加载本地图片文件
2016-09-23 16:23
465 查看
此篇文章主要记录如何在Unity PC环境下加载本地图片
在讲解如何加载本地文件之前,先解决在编译过程可能遇到的一个错误提示:
如下所示:
解决方法如下:
因为 Mono 平台支持 .net 3.5,所以只能使用 NET20 的 System.Windows.Forms.dll导致了此问题。
解决办法:
Unity 菜单 Edit->Project Settings->Player, 在 Player 设置里选择 Api Comatibility Level 从 .NET 2.0 Subset 改为 .NET 2.0。
运行效果如下:
在讲解如何加载本地文件之前,先解决在编译过程可能遇到的一个错误提示:
Unhandled Exception: System.TypeLoadException: Could not load type 'System.ComponentModel.CancelEventHandler' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. ………………………………
如下所示:
解决方法如下:
因为 Mono 平台支持 .net 3.5,所以只能使用 NET20 的 System.Windows.Forms.dll导致了此问题。
解决办法:
Unity 菜单 Edit->Project Settings->Player, 在 Player 设置里选择 Api Comatibility Level 从 .NET 2.0 Subset 改为 .NET 2.0。
using UnityEngine; using System.Collections; using System.Windows.Forms; using System.IO; public class UI_0923 : MonoBehaviour { // Use this for initialization void Start () { } string TexPath; void OnGUI() { if(GUI.Button(new Rect(0,0,50,150),"加载本地图片")) { OpenFileDialog od = new OpenFileDialog(); od.Title = "请选择图片"; od.Multiselect = false; od.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp"; if (od.ShowDialog() == DialogResult.OK) TexPath = od.FileName; if (!File.Exists(TexPath)) Debug.Log("加载失败"); //WWW方式加载图片 //StartCoroutine(WWW_Tex("file://" + TexPath)); //FileStream方式加载图片 FileStreamLoadTexture(); } //WWW方式加载图片——显示 if (wwwTexture != null) { GUI.DrawTexture(new Rect(0, 0, wwwTexture.width, wwwTexture.height), wwwTexture); } //FileStream方式加载图片——显示 if (OriginalTex != null) { GUI.DrawTexture(new Rect(0, 0, OriginalTex.width, OriginalTex.height), OriginalTex); } } /// <summary> /// WWW加载图片 /// </summary> Texture2D wwwTexture; IEnumerator WWW_Tex(string url) { WWW www = new WWW(url); yield return www; if (www.isDone && www.error == null) { wwwTexture = www.texture; } } /// <summary> /// 文件流加载图片 /// </summary> Texture2D OriginalTex; void FileStreamLoadTexture() { //通过路径加载本地图片 FileStream fs = new FileStream(TexPath, FileMode.Open); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); OriginalTex = new Texture2D(2, 2); var iSLoad = OriginalTex.LoadImage(buffer); OriginalTex.Apply(); if (!iSLoad) { Debug.Log("Texture存在但生成Texture失败"); } } }
运行效果如下:
相关文章推荐
- unity实现多点触控代码
- 在Unity中实现动画的正反播放代码
- Unity UGUI教程之实现滑页效果
- unity实现摄像头跟随
- Unity3D上路_01-2D太空射击游戏
- Unity3D上路_02-第一视角射击游戏
- Unity3D上路_03-塔防游戏
- Unity3D上路_04-基础资源介绍
- Unity3D上路_05-网络相关
- Unity3D-5.3.5发布VR项目到Android
- unity 新UI草稿
- [软件资讯]Unity已支持将3D游戏导出成Flash
- ShaderLab: Pass
- Unity 武器拖尾效果
- unity常见问题之20题
- Unity3D与JavaWeb服务器传递数据和文件 ---建立Java服务器
- unity动态加载资源并缓存到本地
- Unity3D动画存储插件
- unity 赛车相机跟随物体移动
- uLua中遇到的问题