Unity的动态添加和删除图片

1、获取StreamingAssets的Content文件夹下的所有图片精灵

public class ImageManage : MonoBehaviour
{
    List<Sprite> imageList = new List<Sprite>();   //加载的图片的列表
    Public List<Image> images = new List<Image>();

void Start()
    {
        //加载所有图片
        LoadAllPic();

        for (int i = 0; i < images.Count; i++)
        {
            int index = i;
            //当图片的数量小于生成的图片存储数组的数量,让图片存储的图片变成第一个
            if (index > imageList.Count - 1)
            {
                index = 0;
            }
            //将图片赋值到预制体上
            images[i].GetComponent<Image>().sprite = imageList[index];
        }
    }
 
#region 外部加载图片
    //外部加载图片
    void LoadAllPic()
    {
        //从StreamingAssets中加载图片
        string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
        string[] ImageType = imgtype.Split('|');
        for (int k = 0; k < ImageType.Length; k++)
        {
            //获取streamingAssets文件夹下所有的图片路径  
            string[] dirs = Directory.GetFiles(Application.streamingAssetsPath+"/Content", ImageType[k]);
            for (int j = 0; j < dirs.Length; j++)
            {
                Texture2D tx = new Texture2D(100, 100);
                tx.LoadImage(getImageByte(dirs[j]));
                Sprite sprite = Sprite.Create(tx, new Rect(0, 0, tx.width, tx.height), new Vector2(-500, -500));
                sprite.name = Path.GetFileNameWithoutExtension(dirs[j]);
                //将获取的图片加到图片列表中
                imageList.Add(sprite);
            }
        }
    }

    private static byte[] getImageByte(string imagePath)
    {
        FileStream files = new FileStream(imagePath, FileMode.Open);
        byte[] imgByte = new byte[files.Length];
        files.Read(imgByte, 0, imgByte.Length);
        files.Close();
        return imgByte;
    }
    #endregion
}

把代码挂载在一个空物体上,再把需要图片赋值的图片放入列表中,就可实现图片精灵的导入。

2、实现图片的动态增加和删除

    //获取streamingAssets/Content里面的所有文件的数量,获取父物体下的所有子物体
    public static void FindAllChildToList<Image>(Transform parent, List<Image> list)
    {
        var path = Application.dataPath + "/streamingAssets/Content";
        if (Directory.Exists(path))
        {
            DirectoryInfo direction = new DirectoryInfo(path);
            FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
            foreach (Transform child in parent)
            {
                //图片数等于场景中的图片组件
                if (parent.childCount == files.Length/2)
                {
                    //将图片放入父物体中
                    Image go = child.GetComponent<Image>();
                    if (go != null)
                    {
                        list.Add(child.GetComponent<Image>());
                    }
                    FindAllChildToList(child, list);
                }

                //图片数小于场景中的图片组件
                if (parent.childCount > files.Length / 2)
                {
                    Debug.Log("image组件多");
                    int num = parent.childCount - files.Length / 2;
                    for (int i = parent.childCount-1; i > num; i--)
                    {
                        Destroy(parent.GetChild(i).gameObject);
                    }

                    //将图片放入父物体中
                    Image go = child.GetComponent<Image>();
                    if (go != null)
                    {
                        list.Add(child.GetComponent<Image>());
                    }
                    FindAllChildToList(child, list);
                }

                //图片数小于场景中的图片组件
                if (parent.childCount < files.Length / 2)
                {
                    Debug.Log("图多");
                    //在content下增加image对象
                    GameObject  projectile = Instantiate(GameObject.Find("Image"),GameObject.Find("Content").transform);
                    Debug.Log(projectile);

                    //修改图片的名字
                    for (int i = 0; i < parent.childCount; i++)
                    {
                        projectile.name = (i+1).ToString();
                    }
                    //添加Button组件
                    projectile.AddComponent<Button>();

                    //将图片放入父物体中
                    Image go = child.GetComponent<Image>();
                    if (go != null)
                    {
                        list.Add(child.GetComponent<Image>());
                    }
                    FindAllChildToList(child, list);
                }
            }
        }
    }

3整体代码

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 图片外部加载和图片的数量的动态添加,删除
/// </summary>
public class ImageManage : MonoBehaviour
{
    List<Sprite> imageList = new List<Sprite>();   //加载的图片的列表
    List<Image> images = new List<Image>();

    void Start()
    {
        //获取content下面的子物体
        FindAllChildToList(transform, images);

        //加载所有图片
        LoadAllPic();

        for (int i = 0; i < images.Count; i++)
        {
            int index = i;
            //当图片的数量小于生成的图片存储数组的数量,让图片存储的图片变成第一个
            if (index > imageList.Count - 1)
            {
                index = 0;
            }
            //将图片赋值到预制体上
            images[i].GetComponent<Image>().sprite = imageList[index];
        }
    }

    #region  获取streamingAssets/Content里面的所有文件的数量,获取父物体下的所有子物体
    public static void FindAllChildToList<Image>(Transform parent, List<Image> list)
    {
        var path = Application.dataPath + "/streamingAssets/Content";
        if (Directory.Exists(path))
        {
            DirectoryInfo direction = new DirectoryInfo(path);
            FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
            foreach (Transform child in parent)
            {
                //图片数等于场景中的图片组件
                if (parent.childCount == files.Length/2)
                {
                    //将图片放入父物体中
                    Image go = child.GetComponent<Image>();
                    if (go != null)
                    {
                        list.Add(child.GetComponent<Image>());
                    }
                    FindAllChildToList(child, list);
                }

                //图片数小于场景中的图片组件
                if (parent.childCount > files.Length / 2)
                {
                    Debug.Log("image组多");
                    int num = parent.childCount - files.Length / 2;
                    for (int i = parent.childCount-1; i > num; i--)
                    {
                        Destroy(parent.GetChild(i).gameObject);
                    }

                    //将图片放入父物体中
                    Image go = child.GetComponent<Image>();
                    if (go != null)
                    {
                        list.Add(child.GetComponent<Image>());
                    }
                    FindAllChildToList(child, list);
                }

                //图片数小于场景中的图片组件
                if (parent.childCount < files.Length / 2)
                {
                    Debug.Log("图多");
                    //在content下增加image对象
                    GameObject  projectile = Instantiate(GameObject.Find("Image"),GameObject.Find("Content").transform);
                    Debug.Log(projectile);

                    //修改图片的名字
                    for (int i = 0; i < parent.childCount; i++)
                    {
                        projectile.name = (i+1).ToString();
                    }
                    //添加Button组件
                    projectile.AddComponent<Button>();

                    //将图片放入父物体中
                    Image go = child.GetComponent<Image>();
                    if (go != null)
                    {
                        list.Add(child.GetComponent<Image>());
                    }
                    FindAllChildToList(child, list);
                }
            }
        }
    }
    #endregion

    #region 外部加载图片
    //外部加载图片
    void LoadAllPic()
    {
        //从StreamingAssets中加载图片
        string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
        string[] ImageType = imgtype.Split('|');
        for (int k = 0; k < ImageType.Length; k++)
        {
            //获取streamingAssets文件夹下所有的图片路径  
            string[] dirs = Directory.GetFiles(Application.streamingAssetsPath+"/Content", ImageType[k]);
            for (int j = 0; j < dirs.Length; j++)
            {
                Texture2D tx = new Texture2D(100, 100);
                tx.LoadImage(getImageByte(dirs[j]));
                Sprite sprite = Sprite.Create(tx, new Rect(0, 0, tx.width, tx.height), new Vector2(-500, -500));
                sprite.name = Path.GetFileNameWithoutExtension(dirs[j]);
                //将获取的图片加到图片列表中
                imageList.Add(sprite);
            }
        }
    }

    private static byte[] getImageByte(string imagePath)
    {
        FileStream files = new FileStream(imagePath, FileMode.Open);
        byte[] imgByte = new byte[files.Length];
        files.Read(imgByte, 0, imgByte.Length);
        files.Close();
        return imgByte;
    }
    #endregion
}

4 效果展示

1当图片数量跟场景中图片数量一致时

 2当图片数量小于跟场景中图片数量时

未运行时

 运行之后

3当图片数量大于跟场景中图片数量时

未运行时

 运行之后

猜你喜欢

转载自blog.csdn.net/shijinlinaaa/article/details/126269784