1. 程式人生 > 實用技巧 >unity 載入圖片,並且圖片不在resource、StreamingAssets裡面。

unity 載入圖片,並且圖片不在resource、StreamingAssets裡面。

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public  enum UI_name{
    UpBtn,
    DownBtn,
    SubmitBtn
}

public class ExplainFun : MonoBehaviour {

    public Image ShowPic;
    public UI_name UiName;

    public float picTotalNum;


    
private float picNum = 5; private string filePath; private FileInfo[] files; void Start () { switch (UiName) { case UI_name.UpBtn: EventTriggerListener.Get(gameObject).onClick = onUpBtn; break; case UI_name.DownBtn: EventTriggerListener.Get(gameObject).onClick
= onDownBtn; break; case UI_name.SubmitBtn: EventTriggerListener.Get(gameObject).onClick = onSubmit; break; default: break; } filePath = Application.dataPath+ "/切削力和切削溫度測量虛擬模擬實驗 內頁切圖/2/"; }
// Update is called once per frame void onUpBtn(GameObject sender) { picNum--; Debug.Log(picNum); if (picNum <= 0) { picNum = 0; } FileStream fs = new FileStream(filePath + picNum + ".png", FileMode.Open, FileAccess.Read); byte[] buffur = new byte[fs.Length]; fs.Read(buffur, 0, buffur.Length); fs.Close(); Texture2D texture = new Texture2D(10, 10); texture.LoadImage(buffur);//流資料轉換成Texture2D //建立一個Sprite,以Texture2D物件為基礎 Sprite sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero); ShowPic.GetComponent<Image>().sprite = sp; } void onDownBtn(GameObject sender) { picNum++; if (picNum >= picTotalNum) { picNum = picTotalNum; } } void onSubmit(GameObject sender) { } }

優點是減少釋出出來的exe大小

缺點是不能隨著一起釋出 出來。