这个文件夹下加载批量图片,可以随时更新图片,加或者删除;
首先创建这个文件夹StreamingAssets,如下图
不同的文件夹下放入了不同的图片内容;
然后开始创建LoadPanel.cs
主要是加载图片:
private void LoadByPath(string path,GameObject content)
{
string ur = urls + "/" + path;
if (Directory.Exists(ur))
{
DirectoryInfo direction = new DirectoryInfo(ur);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
Array.Sort(files, new FileNameSort());
int temp = 0;
for (int i = 0; i < files.Length; i++)
{
Debug.Log("Name:" + files[i].Name); //打印出来这个文件夹下的所有文件
if (files[i].Name.EndsWith(".meta"))
{
continue;
}
else
{
temp++;
}
}
length = temp;
fileNames = new string[length];
Images = new GameObject[length];
int k = 0;
for (int i = 0; i <files.Length; i++)
{
if (files[i].Name.EndsWith(".meta"))
{
continue;
}
// Debug.Log("Name:" + files[i].Name); //打印出来这个文件夹下的所有文件
fileNames[k] = files[i].Name;
k++;
}
}
StartCoroutine(ContentLoad(path, content));
}
private void SortAsFileName(ref FileInfo[] arrFi)
{
Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return x.Name.CompareTo(y.Name); });
}
private IEnumerator ContentLoad(string path,GameObject content)
{
string ur = urls + "/" + path;
for (int l = 0; l < length; l++)
{
var oj = Resources.Load("Prefabs/Image", typeof(GameObject));
Images[l] = Instantiate(oj) as GameObject;
Images[l].transform.parent = content.transform;
Images[l].GetComponent<RectTransform>().sizeDelta = new Vector2(1920, 1080);
WWW www = new WWW(ur + "/" + fileNames[l]);//只能放URl
Images[l].gameObject.name = fileNames[l].Substring(0, fileNames[l].Length-4);
yield return www;
if (www != null && string.IsNullOrEmpty(www.error))
{
Texture2D texture = www.texture;
//创建 Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 1920, 1080), new Vector2(0.5f, 0.5f));
Images[l].GetComponent<Image>().sprite = sprite;
Images[l].GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
Vector3 v3 = Images[l].GetComponent<RectTransform>().localPosition;
Images[l].GetComponent<RectTransform>().localPosition = new Vector3(v3.x, v3.y, 0);
if (fileNames[l].Equals("2福州涉台文物古迹_1.png"))
{
Images[l].gameObject.AddComponent<Button>().onClick.AddListener(tPscan);
}
//double time = (double)Time.time - startTime;
//Debug.Log("WWW加载用时:" + time);
}
}
}
首先从相应的文件夹下获取图片的数量,然后一一加载出来,这里加载图片只能在主线程中加载,不能使用子线程,所以这里应用了协程,加载需要耗费时间;