Resource Management in Unity - Using Profile to Analyze Memory Usage

This article shares resource management in Unity - using Profile to analyze memory usage

In the previous article, we introduced Abthe loading and usage of , and briefly listed its memory distribution. Today we continue to explore Abthe memory, observe and experiment with its distribution in various stages.

Profile performance analysis tool

Before everything starts, let's briefly introduce the performance analysis tool provided by Unity: Profile .

Profile is a performance analysis tool provided by Unity. It is released together with Editor. We can find it under the Window menu. Different versions have different locations, such as in Unity2017 (Window->Profile), and in Unity2019 (Window->Analysis- >Profile).

After opening, it is shown in the figure (this article is based on Unity2019.4.26f1, different versions will be different, but the same):

insert image description here

We focus on the menu on the left:

  • CPU Stage : CPU usage
  • Rendering : Rendering situation
  • Memory : memory condition

After each menu is clicked, the description panel below has a corresponding summary description.

Note that this article only focuses on the memory part. The situation in other parts is similar, you can explore by yourself, the portal is here .

After selecting the memory menu, the description panel below can have two views, namely: Simple (simple description), Detailed (details).

The Simple view shows a summary of Unity's real-time memory information in each frame. Unity will apply for reserved memory from the system in advance to reduce frequent memory requests. This view only shows the amount of memory usage of each type without involving specific details.

The displayed information includes the following:

  • first row:
    • Used Total : the sum of all subsequent memory, as shown above: (Unity+Mono+GfxDriver+Audio+Video+Profile=341.6M)
    • Unity : The memory size used by Unity's native code
    • Mono : the amount of memory used by managed code
    • GfxDriver : Estimated amount of memory used by the driver for textures, render targets, shaders and mesh data
    • Audio/Video : The memory size used by the audio and video system
    • Profiler : The total memory size used by the profiler
  • The second line: Similar to the first line, it just describes the reserved memory that Unity applies to the system.
  • The third line: The memory size used by the entire system is consistent with the size used in the task manager. Depending on whether the platform allows the memory to be obtained from the system, this value will display different sizes. Generally, it will be greater than the sum of the previous two lines. Because Profile cannot track all the memory.
  • More lines: The rest of the information is clear at a glance, including the memory size occupied by different types of resources, and the number of game objects and other basic information, which will not be repeated here.

The Detailed view shows the details of memory usage. Because of the huge amount of information, a screenshot sampling (or snapshot) method (Take Sample) is used to capture a certain frame for analysis. At the same time, after checking the upper middle part, more information can be Deep Profileobtained , enable Gather object referencesto collect the possible reference information of the object, as shown in the figure below:
insert image description here

The memory details are divided into several parts, which are:

  • Other : Resources, memory of objects other than game objects or components, such as system libraries, Profiler, various managers, etc.
  • Not Saved : The object marked as HideFlags.DontSave, that is, the object that is not saved to the scene, and will not be destroyed when loading a new scene, is 是 HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor | HideFlags.DontUnloadUnusedAsseta combination.
  • Assets : Resources referenced from users or native code, this is the key part we focus on.
  • Scene Memory : Objects of the current scene and their attached resources
  • Builtin Resources : Unity Editor or Unity built-in resources

Analyze Ab memory usage

With the pre-knowledge of Profile , we can officially start the analysis.

Our purpose is to observe the changes in memory at each stage.

For testing, we need a test program that contains:

  • loadAb
  • Load textures (assets that don't require instancing)
  • Load prefabs (requires instantiated assets)
  • instantiated object
  • destroy object
  • uninstall prefab
  • unload texture
  • Unload Abwithout destroying assets and objects
  • unload Ab, destroy assets and objects

Each stage corresponds to a button and callback, the effect is as follows:

insert image description here

Delete and mount the control script on Controllerthe object:ResourcesTest

public class ResourcesTest : MonoBehaviour {
    public Button btnClear;
    public Button btnLoadAb;
    public Button btnLoadTexture;
    public Button btnLoadPrefab;
    public Button btnInstanceObj;
    public Button btnDestroyObj;
    public Button btnUnloadPrefab;
    public Button btnUnloadTexture;
    public Button btnUnloadAb;
    public Button btnUnloadAbAndDestroy;

    private AssetBundle m_Ab;
    private GameObject m_Prefab;
    private GameObject m_Obj;
    private Texture m_Texture;
    
    void Start() {
        btnClear.onClick.AddListener(Clear);
        btnLoadAb.onClick.AddListener(LoadAb);
        btnLoadTexture.onClick.AddListener(LoadTexture);
        btnLoadPrefab.onClick.AddListener(LoadPrefab);
        btnInstanceObj.onClick.AddListener(InstanceObj);
        btnDestroyObj.onClick.AddListener(DestroyObj);
        btnUnloadPrefab.onClick.AddListener(UnloadPrefab);
        btnUnloadTexture.onClick.AddListener(UnloadTexture);
        btnUnloadAb.onClick.AddListener(() => UnloadAb(false));
        btnUnloadAbAndDestroy.onClick.AddListener(() => UnloadAb(true));
    }

    void Clear() {
        Resources.UnloadUnusedAssets();
    }
    
    void LoadAb() {
        UnloadAb(true);
        
        var ab = AssetBundle.LoadFromFile("Assets/Output/AssetBundle/AllAb/prefabs");
        m_Ab = ab;
        
        Assert.IsNotNull(m_Ab);
    }

    void LoadTexture() {
        m_Texture = m_Ab.LoadAsset<Texture>("Common_Logo");
        Assert.IsNotNull(m_Texture);
    }
    
    void LoadPrefab() {
        m_Prefab = m_Ab.LoadAsset<GameObject>("Attack");
        Assert.IsNotNull(m_Prefab);
    }
    
    void InstanceObj() {
        m_Obj = Instantiate(m_Prefab);
        Assert.IsNotNull(m_Obj);
    }
    
    void DestroyObj() {
        if (m_Obj != null) {
            Destroy(m_Obj);
            m_Obj = null;
        }
    }

    void UnloadPrefab() {
        m_Prefab = null;
        Resources.UnloadUnusedAssets();
    }
    
    void UnloadTexture() {
        Resources.UnloadAsset(m_Texture);
        m_Texture = null;
    }
    
    void UnloadAb(bool needDestroy = false) {
        if (m_Ab != null) {
            m_Ab.Unload(needDestroy);
            m_Ab = null;
        }
    }

    private void OnDestroy() {
        UnloadAb(true);
    }
}

Test in stages

Initially, after startup, we first clean up all useless resources (click 清理the button) and record a memory snapshot:

insert image description here

Load and unload Ab

After clicking 加载Abthe button:

insert image description here

We see that the number of Other and Not Saved has increased by one, and after some comparison after expansion, it is found that the increase is:

insert image description here
insert image description here

Because Abit is a serialized file itself, an object is added in . At the same time Other, this is added in .SerializedFileNot SavedAssetbundleAb

After clicking 卸载Abor 卸载Ab(不摧毁资材和对象)after, the memory is restored. Because no assets or instantiated objects have been loaded here, all two unloading methods behave the same.

Load and unload textures

Because under the Editor, there will be subtle differences after each startup, so we Abstart with loading at each stage.

After restarting and cleaning:
insert image description here

After loading Ab:
insert image description here

Click on 加载纹理:

insert image description here

Other and Not Saved have not changed, and the number of Assets has increased by 2, which is the texture resource and sprite corresponding to the texture (the resource tested is sprite).

If you click 清理the button now, the memory will not change, because Texture is referenced by local variables and will not be cleaned up.

After clicking 卸载Ab(不摧毁资材和对象)the button, Abit is unloaded, but the texture still exists.

insert image description here

After cleaning and reloading Aband texture, 卸载Abafter clicking the button, Abit is unloaded, and the texture is also unloaded, returning to Abthe state before loading.

After cleaning and reloading Abthe texture, 卸载纹理after clicking the button, the texture is unloaded and restored to the state before the texture was loaded.

Load and unload prefabs

A prefab is an asset that needs to be instantiated, and because it generally contains many references to other assets, once the prefab is loaded, all its references will be loaded into memory at the same time.

After restarting and cleaning:

insert image description here

After loading Ab:

insert image description here

After clicking 加载预制the button:

insert image description here

A total of 41 Assets have been added, because the prefab references more resources, including textures, objects, materials, shaders, etc.

After clicking 卸载预制之后the button, Assets returns to its original size, but Other has increased. After careful comparison, the author did not find where the enlarged part is. I hope that students who know more will tell in the comment area.

After reloading the prefab, 卸载Ab(不摧毁资材和对象)after clicking the button, the prefab and its reference resources still exist and Abare unloaded.

After reloading the prefab, the prefab is unloaded along 卸载Abwith its assets when the button is clicked.Ab

Loading and unloading prefabs plus instantiating objects

After restarting, cleaning, loading Aband prefab:

insert image description here
insert image description here

Not Saved and Scene Memory have changed.

Not Saved adds 2, from two shades:

insert image description here

Scene Memory has been increased by 22, various assets and instantiated objects from object references:
insert image description here

After clicking 摧毁对象the button, Not Saved and Scene Memory are restored to size.

After reloading the prefab, 卸载Ab(不摧毁资材和对象)after clicking the button, the prefab, its reference resources and instantiated objects still exist and Abare unloaded.

After reloading the prefab and clicking 卸载Abthe button, its referenced resources and instantiated objects Abwill be unloaded together. But the variable reference of the object is not removed, so the part managed by Scene Memory cannot be cleaned up, and the size of Scene Memory cannot be restored.

In short, when unloading Ab, if you want to destroy the loaded material and the instantiated resource at the same time, you need to pay attention to clean up all references, otherwise there may be serious problems.

Summarize

Today I introduced Unity's performance analysis tool: Profile , and provided a simple example for analyzing Abmemory conditions in various stages and situations.

Because the entire analysis process is a dynamic process, it is difficult to use articles to express clearly, resulting in a lot of content that cannot be introduced clearly.

The dynamic analysis articles are relatively dry, and even fewer can be clearly written. The video introduction is more convenient. If there is a chance, I will record it for everyone.

Interested students can build their own test cases for analysis based on today's content, and they will surely gain something of their own.

The next stage will be the content of the last part of this column: a commercial resource management solution.

It's the end of the year, and the company's business is busy. I hope it can be updated before the new year. If you really don't have time, you can only wait for next year.

Well, that's all for today's content. For this article, the author lost a few strands of hair. I hope it will be helpful to everyone!

Guess you like

Origin blog.csdn.net/woodengm/article/details/122208495