Unity 通过图片加载来显示内存的变化(Resources.load版)

Unity 通过图片加载来显示内存的变化

写一个Demo,把一张图片资源从硬盘上,载入到内存,然后显示在界面上,然后再清理释放,每一个环节用一个按钮点击Next出发来完成完成资源载入卸载单步调试,检查profiler内存情况
首先进行基本的UI界面编写,这里使用NGUI插件,添加背景图片,添加button。这里不多赘述。
要注意的是:要实现一个Texture的加载—>显示—>消除过程,则要把Texture落到Resource文件夹中成为一个预制体,后来在后面的加载操作中使用
UI界面

调配设置好UI界面后,进行button脚本的编写
脚本代码如下:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LoadButton : MonoBehaviour {

    public Text text;
    UITexture load_texture;
    UITexture create_texture;
    int i = 0;

    public void OnClick()
    {
        i = i + 1;          //对按钮次数进行选择
        int x = i % 3;
        switch (x)
        {
            case 1:
                Load_texture();
                break;
            case 2:
                Create_texture();
                break;
            case 0:
                Destory_texture();
                break;
            default:
                break;
        }
    }
    void Load_texture()
    {
        //加载图片
        load_texture = Resources.Load<UITexture>("Prefab/1");
        text.text = "Create";
    }

    void Create_texture()
    {
      //创建显示图片
        if (load_texture != null)
        {
            create_texture = Instantiate(load_texture, transform.position, Quaternion.identity) as UITexture;
            text.text = "Destory";
        }
    }

    void Destory_texture()
    {

       //删除图片
        if (load_texture != null && create_texture != null)
        {
            DestroyObject(create_texture.gameObject);
            load_texture = null;
            create_texture = null;

            Resources.UnloadUnusedAssets();    //从内存中卸载,必须将load_texture等设置为null
            text.text = "Load";
        }
    }


}

通过记录button的点击次数来进行按钮功能的切换
Load_texture()函数中使用Resources.Load进行加载,但不立刻显示出来
点点击button时,i值变化,跳转执行Create_texture()函数
Create_texture()函数是对上一个函数的执行结果进行判空操作,若不为空,则通过Instantiate实例化Texture。

static function Instantiate (original : Object, position : Vector3, rotation : Quaternion) : Object
其中Object为要实例化的东西,position、rotation为坐标和旋转角度

Destory_texture()为销毁函数,这里要注意的是使用Resources.UnloadAsset()对load_texture进行卸载操作时,看起来是卸载了,但实际上通过Profiler进行内存监测时发现并没有效果,后采用Resources.UnloadUnusedAssets()对所有已加载的Object先进行赋NULL操作,再进行卸载操作。

以下为运行时依次点击按钮3次,内存的变化(注意红框):

Start:
这里写图片描述

Load:
这里写图片描述

Create:
这里写图片描述

Destory:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/znwhahaha/article/details/81186973