using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
public class TestLoading : MonoBehaviour
{
/// <summary>
/// Image控件
/// </summary>
private Image image;
void Start ()
{
image = this.transform.Find("Image").GetComponent<Image>();
//为不同的按钮绑定不同的事件
this.transform.Find("LoadByWWW").GetComponent<Button>().onClick.AddListener
(
delegate(){LoadByWWW();}
);
this.transform.Find("LoadByIO").GetComponent<Button>().onClick.AddListener
(
delegate(){LoadByIO();}
);
}
/// <summary>
/// 以IO方式进行加载
/// </summary>
private void LoadByIO()
{
double startTime = (double)Time.time;
//创建文件读取流
FileStream fileStream = new FileStream("D:\\test.jpg", FileMode.Open, FileAccess.Read);
fileStream.Seek(0, SeekOrigin.Begin);
//创建文件长度缓冲区
byte[] bytes = new byte[fileStream.Length];
//读取文件
fileStream.Read(bytes, 0, (int)fileStream.Length);
//释放文件读取流
fileStream.Close();
fileStream.Dispose();
fileStream = null;
//创建Texture
int width = 300;
int height = 372;
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes);
//创建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
startTime=(double)Time.time-startTime;
Debug.Log("IO加载用时:" + startTime);
}
/// <summary>
/// 以WWW方式进行加载
/// </summary>
private void LoadByWWW()
{
StartCoroutine(Load());
}
IEnumerator Load()
{
double startTime = (double)Time.time;
//请求WWW
WWW www = new WWW("file://D:\\test.jpg");
yield return www;
if(www != null && string.IsNullOrEmpty(www.error))
{
//获取Texture
Texture2D texture=www.texture;
//创建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
startTime = (double)Time.time - startTime;
Debug.Log("WWW加载用时:" + startTime);
}
}
}
Unity调试函数执行时间
最新推荐文章于 2023-09-19 16:38:21 发布