[Unity] 文件夹图像资源的读取

来源:互联网 发布:网络视频赌博骗局 编辑:程序博客网 时间:2024/05/15 23:45

注意文件以及文件夹必须寄宿在Resources目录下,才能顺利调用Resources.Load()和Resources.loadAll()这两个函数得到所需要的图像文件。

 

 

public class GUITest : MonoBehaviour {

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }


    private Texture2D texSingle;
    private Texture2D[] texAll;

    void OnGUI()
    {

        if (GUI.Button(new Rect(0,10,100,50),"加载一张贴图"))
        {
            if (texSingle==null)
            {
                texSingle = Resources.Load("single/0") as Texture2D;   //这里不需要加后缀
            }
           
        }
        if (GUI.Button(new Rect(0,130,100,50),"加载一组贴图"))
        {
            if (texAll==null)
            {                
                var textures = Resources.LoadAll("textures");
                int countAll=textures.Length;
                texAll=new Texture2D[countAll];
                for (int i = 0; i < countAll; i++)
                {
                    texAll[i] = textures[i] as Texture2D;
                }

            }
        }

        //绘制贴图
        if (texSingle!=null)
        {
            GUI.DrawTexture(new Rect(110,10,80,80),texSingle,ScaleMode.ScaleToFit,true,0);
        }
        if (texAll!=null)
        {
            int countOfAll = texAll.Length;
            for (int i = 0; i < countOfAll; i++)
            {
                GUI.DrawTexture(new Rect(110+i*80,130,80,80),texAll[i],ScaleMode.ScaleToFit,true,0);
            }
        }
    }
}