using System.Collections.Generic;
using UnityEngine;
using System.IO;
/// <summary>
/// 獲取StreamingAssets中的文件的名稱
/// </summary>
public class GetStreamingAssetsName : MonoBehaviour {
private List<Texture> tex = new List<Texture>();
private List<string> strList = new List<string>();
public Texture[] texArray;
public string[] strArray;
// Use this for initialization
void Start () {
LoadPicturesOfStreamingAssets();
Debug.Log(Application.streamingAssetsPath);
}
// Update is called once per frame
void Update () {
}
/// <summary>/// 從StreamingAssets中讀取圖片
/// </summary>
void LoadPicturesOfStreamingAssets()
{
StartCoroutine(Load_WWW_AllPicture());
}
IEnumerator Load_WWW_AllPicture()
{
string streamingAssetsPath = Application.streamingAssetsPath; //所有的文件的路徑
//string streamingAssetsPath = Application.streamingAssetsPath + "/" + "Textures"; //單個文件夾的文件的路徑
DirectoryInfo dir = new DirectoryInfo(streamingAssetsPath); //初始化一個目錄信息類的對象 //Directory:目錄 info:信息
GetAllFiles(dir);
foreach(DictionaryEntry de in hashtable)
{
WWW www = new WWW("file://" + streamingAssetsPath + "/" + de.Key); //獲取文件名稱對應的文件
yield return www;
if (www != null)
{
tex.Add(www.texture);
}
if (www.isDone)
{
www.Dispose();
Debug.Log("找到一張圖片");
}
}
Debug.Log("圖片尋找完畢");
if (tex.Count != 0)
{
texArray = tex.ToArray();
}
if (strList.Count != 0)
{
strArray = strList.ToArray();
for (int i = 0; i < strArray.Length; i++)
{
Debug.Log("圖片名稱是:"+ strArray[i]);
}
}
}
Hashtable hashtable = new Hashtable();
void GetAllFiles(DirectoryInfo dir)
{
FileSystemInfo[] fileSystemInfo = dir.GetFileSystemInfos(); //初始化一個FileSystemInfo類型的實例
foreach(FileSystemInfo info in fileSystemInfo) //遍歷 DirectoryInfo 下的所有內容
{
if(info is DirectoryInfo) //當在 DirectoryInfo 中存在 info 時
{
GetAllFiles((DirectoryInfo)info); //獲取 info 下的所有文件
}
else
{
string str = info.FullName; //記錄 info 的絕對路徑
string path = Application.streamingAssetsPath;
//string path = Application.streamingAssetsPath + "/" + "Textures";
string strType = str.Substring(path.Length); //將文件的名稱記錄
//通過文件的名稱的最後3位,辨別文件的類型
if(strType.Substring(strType.Length-3).ToLower()=="png"|| strType.Substring(strType.Length - 3).ToLower() == "jpg")
{
if (hashtable.Contains(strType)) //判斷當前哈希表中是否存在這個值
{
hashtable[strType] = strType; //將該文件的名稱作爲鍵,存儲在哈希表中
}
else
{
hashtable.Add(strType, strType); //如果不存在,添加這個鍵和值
//strList.Add((strType.Remove(0,1)).Remove((strType.Remove(0, 1)).Length-4,4)); //將圖片名稱添加到數組中
strList.Add(strType.Remove(strType.Length - 4, 4).Remove(0,1));
}
}
}
}
}
}