unity一次性多图加载最节省CPU的方式异步加载图片

这几天遇到了一个问题,就是在StreamingAssets路径下放了十几张图片,但是直接读取的话会卡顿十几秒二十几秒,用户电脑差的话可能得将近一分钟,最后想了两种加载方式。

第一:在刚打开软件的时候或者跳转场景的时候,进行图片预生成,因为在这时候加载慢一点用户也没什么感觉,但是由于我的图片是需要用户自己去进行添加,如果用这种方式的话,后面用户添加的图片多了,可能会造成卡顿更严重的现象。

第二:这一种呢是用异步加载的方式来加载图片的,优点是跳转界面后很快的会加载到界面,缺点是跳转过去之后一张一张加载

代码如下:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

public class PictureChange : MonoBehaviour
{

    private string[] dirs = new string[] { };// //获取文件夹下所有的图片路径  
    public static List<Texture2D> allTex2d = new List<Texture2D>(); // 储存获取到的图片  

    public GameObject tupian;//实例化图片
    public static int pictureNumber = 0;//文件夹中图片的个数



    // Start is called before the first frame update
    void Start()
    {

        //pictureTrue();

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {

            load();

        }
        if (Input.GetKeyDown(KeyCode.B))
        {

            //pictureTrue();
            UniteFSAsync();
        }
    }

    /// <summary>
    /// 获取图片个数,并存储
    /// </summary>
    private void load()
    {
        List<string> filePaths = new List<string>();
        string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
        string[] ImageType = imgtype.Split('|');
        int number = 0;//个数存储


        //int count = 0;
        //if (int.TryParse(IniReader.ReadOption("Movie", "Count", string.Empty), out count))
        //{
        //    for (int i = 1; i <= count; i++)
        //    {
        //        string str = "Movie" + i.ToString();
        //        string moviePath = IniReader.ReadOption("Movie", str, string.Empty);

        //    }
        //}


        for (int i = 0; i < ImageType.Length; i++)
        {
            //获取文件夹下所有的图片路径  
            dirs = Directory.GetFiles(Application.streamingAssetsPath + "/MaterialImg", ImageType[i]);

            for (int j = 0; j < dirs.Length; j++)
            {
                filePaths.Add(dirs[j]);
            }
            number += dirs.Length;//不同类型的图片累计增加
        }


        for (int i = 0; i < filePaths.Count; i++)
        {
            Texture2D tx = new Texture2D(100, 100);
            tx.LoadImage(getImageByte(filePaths[i]));
            allTex2d.Add(tx);
        }


        pictureNumber = number;//传递图片个数
        Debug.Log("图片的个数:" + pictureNumber);

    }
    /// <summary>  
    /// 根据图片路径返回图片的字节流byte[]  
    /// </summary>  
    /// <param name="imagePath">图片路径</param>  
    /// <returns>返回的字节流</returns> 
    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;
    }

    /// <summary>
    /// 统一异步载入
    /// </summary>
    public async void UniteFSAsync()
    {

        //scrollView.SetActive(true);
        for (int i = 0; i < allTex2d.Count; i++)
        {
            GameObject tf = Instantiate(tupian, transform);
            //tf.GetChild(1).GetComponent<Text>().text = mt.Name;
            //tf.GetChild(2).GetComponent<Text>().text = mt.Description;
            Image image = tf.transform.GetChild(0).GetComponent<Image>();

            await LoadByFSAsync(dirs[i], image);
        }

    }

        /// <summary>
        /// 异步载入图片
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="image">Image对象</param>
        /// <returns></returns>
        async Task LoadByFSAsync(string path, Image image)
    {
        
        byte[] result;

        using (FileStream SourceStream = File.Open(path, FileMode.Open))
        {
            result = new byte[SourceStream.Length];
            await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
        }
        int width = 300;
        int height = 372;
        Texture2D tx = new Texture2D(width, height);
        tx.LoadImage(result);
        image.sprite = Sprite.Create(tx, new Rect(0, 0, tx.width, tx.height), new Vector2(0.5f, 0.5f));
    }



}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的小石头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值