Unity 中加载外部图片文件,可动态更换图片

根据自己的项目需求灵活地调整代码逻辑

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

/// <summary>
/// 此类为加载外部图片文件,可动态替换图片---
/// 第一种方法:首先获取文件夹中所有文件名称,将其添加到Image列表中,根据列表加载文件夹中的图片--
/// 第二种方法:直接获取文件夹中的文件名称,根据文件名称下载对应的图片--
/// </summary>
public class LoadTextureManager : MonoBehaviour
{
    [Header("图片的父物体")]
    [SerializeField]
    private Transform imageRoot;

    private List<string> imgNameList = new List<string>();

    void Start()
    {
        #region 第一种方法
        //GetAllImageName("Citys");
        //GetAllImage("Citys");
        #endregion

        #region 第二种方法
        GetAllImageName("Citys");
        #endregion
    }

    #region 获取文件夹中文件的名称相关函数
    /// <summary>
    /// 获取文件夹中所有的图片名称
    /// </summary>
    /// <param name="floderName">文件夹名称</param>
    private void GetAllImageName(string floderName)
    {
        if (string.IsNullOrEmpty(floderName))
        {
            Debug.LogError($"floderName的值为空{floderName},请输入正确的文件夹名称!!");
        }
        else
        {
            string loadPath;//读取文件的路径
            if (Application.platform == RuntimePlatform.Android)
            {
                loadPath = "/storage/emulated/0/" + floderName;
                //Debug.LogError($"安卓端图片读取::{loadPath},");
            }
            else
            {
                loadPath = Application.streamingAssetsPath + "/" + floderName;
                //Debug.Log($"PC端图片读取::{loadPath},");
            }
            //判断floderName文件夹是否存在
            if (Directory.Exists(loadPath))
            {
                DirectoryInfo direction = new DirectoryInfo(loadPath);
                FileInfo[] fileInfos = direction.GetFiles("*", SearchOption.AllDirectories);
                if (fileInfos.Length.Equals(0))
                    Debug.LogError(floderName + "文件夹为空");
                for (int i = 0; i < fileInfos.Length; i++)
                {
                    if (fileInfos[i].Name.EndsWith(".png"))
                    {
                        string imgName = fileInfos[i].Name;
                        AddImageName(imgName);
                        #region 第二种方法
                        DownloadTexture(floderName, imgName);
                        #endregion
                    }
                    else if (fileInfos[i].Name.EndsWith(".jpg"))
                    {
                        string imgName = fileInfos[i].Name;
                        AddImageName(imgName);
                        #region 第二种方法
                        DownloadTexture(floderName, imgName);
                        #endregion
                    }
                }
            }
        }
    }

    /// <summary>
    /// 将文件夹中文件的名称添加到列表中
    /// </summary>
    /// <param name="_name"></param>
    private void AddImageName(string _name)
    {
        if (!imgNameList.Contains(_name))
        {
            imgNameList.Add(_name);
        }
        else
        {
            Debug.LogError("重名图片,请检查:" + _name);
        }
    }
    #endregion

    #region 下载图片相关函数
    /// <summary>
    /// 获取文件夹中所有图片
    /// </summary>
    /// <param name="floderName"></param>
    public void GetAllImage(string floderName)
    {
        if (string.IsNullOrEmpty(floderName))
        {
            Debug.LogError($"floderName的值为空{floderName},请输入正确的文件夹名称!!");
        }
        else
        {
            for (int i = 0; i < imgNameList.Count; i++)
            {
                DownloadTexture(floderName, imgNameList[i]);
            }
        }
    }

    /// <summary>
    /// 开始协同程序下载图片
    /// </summary>
    /// <param name="floderName"></param>
    /// <param name="imgName"></param>
    private void DownloadTexture(string floderName, string imgName)
    {
        StartCoroutine(IEDownloadTexture(floderName, imgName));
    }

    /// <summary>
    /// UnityWebRequest下载图片--
    /// </summary>
    /// <param name="floderName">文件夹名称</param>
    /// <param name="imgName"></param>
    /// <returns></returns>
    private IEnumerator IEDownloadTexture(string floderName, string imgName)
    {
        string path = /*"file:///" +*/ Application.streamingAssetsPath + "/" + floderName + "/" + imgName;
        using (UnityWebRequest wr = UnityWebRequestTexture.GetTexture(path))
        {
            yield return wr.SendWebRequest();
            if (!wr.isNetworkError || !wr.isHttpError)
            {
                Texture2D texture = DownloadHandlerTexture.GetContent(wr);
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1f);
                CreateImage(sprite, imgName);
            }
            else
            {
                Debug.LogError(wr.error);
            }
        }
    }

    /// <summary>
    /// 创建新的Image
    /// </summary>
    /// <param name="sprite"></param>
    private void CreateImage(Sprite sprite, string _Name)
    {
        GameObject gameObject = new GameObject(); //新建一个物体
        string[] strArray = _Name.Split('.');
        string imgName = strArray[0];
        gameObject.name = imgName;
        gameObject.AddComponent<Image>().sprite = sprite;//将下载的图片添加到物体Iamge中

        if (imageRoot != null)
            gameObject.transform.SetParent(imageRoot);//设置新建物体的父类
    }
    #endregion
}

猜你喜欢

转载自blog.csdn.net/U3DCoder/article/details/123901549
今日推荐