Unity Performance Optimization

In general, the performance optimization of the project through Unity can be divided into the following parts:

  • resources
  • Apply colours to a drawing
  • The program
  • Project configuration

In this part, resource performance optimization belongs to the most basic, the most effective means of optimization, but also the game developers need to pay attention to the daily development of a part of the most, so this article will simply introduce the operation of resources need to pay attention to what points

1. Texture (simply speaking, picture)

Resource optimization of texture mainly focuses on the following points:

  • Grain size
  • Compressed format
  • Import Settings

Usually, most of the memory is used for textures while the game is running, so your import Settings are criticalInspectorThe panel sees information about the image resource, similar to the image below:

From the perspective of performance optimization, texture import should follow the following principles:

  • Reduce maximum resolution
  • Using the quadratic power compression format:
  • Create a texture atlas
  • Uncheck theRead/Write Enabled
  • Disable redundantMip Map:Mip MapTextures in 2D sprites andUIGraphics of this size are not always useful for textures

1. Reduce the maximum resolution

Understandably, the higher the resolution of a texture, the more memory it takes up while the game is running, and the amount of memory it takes up is proportional to the square of its resolution. In other words, if the resolution is twice as high, four times as much memory is consumed. Therefore, it needs to be limited from the perspective of resource optimization. To put it simply, the texture of a Button is usually lower than 128X128, so using 1024X024 will cause a waste of performance

In the following image, you can see it in the bottom property of the Inspector: Max Size. You can also see that the maximum resolution can be selected for different platforms:

First picture:Max SizeAdjusted for1024, the texture resource size is4.9 MB

Second picture:Max SizeAdjusted for512, image resource size is1.3 MB

2. Compression of texture

Before you take the initiative to choose a compression format,UnityIt does something to the image itself, whatever you put inPNG,JPG,PSDorTGA.UnityWill manually help us adjust toTexture 2D, this is a simple scheduling strategy:

So why give developers the option of choosing a compression format when Unity is already converting intelligently? Why not just wrap the compression method in Texture 2D?

Actually Unity relative to other development engine has an obvious advantage, it is much fitment, so in order to achieve this much fitment, targeted for a single platform will be relatively less, and the performance of the different platforms and different, requires developers to choose according to characteristics of platform for gaming platform compressed format.

Again, even in the same platform, can also according to different situations with different compression requirements, such as there are some key main page picture, players awareness is strong, is some taller requirement about the quality of the images, some pieces of supporting images, as may be required is lower, if use compression, quality performance creates waste, but if the compression is done with low quality, The quality can’t keep up. Therefore, you also need to select different compression formats based on actual requirements.

When talking about Unity image compression, we often see such a picture to introduce the characteristics and applicable scenarios of different compression formats. I am also baidu Picture directly climbed this picture, we can refer to it (if there is infringement, please inform me, I will delete it immediately).

Before understanding the above picture, a simple calculation, a 1024 by 1024 RGBA32 format image occupies the storage space:

Since RGBA32 is A pixel each color value is composed of two hexadecimal numbers, namely 8 bits, that one pixel is 8 bits multiplied by 4 color values R, G, B, A is 4 bytes, namely 4B, then multiplied by 1024*1024 pixels, the final size is 4MB, namely 4 megabytes. This is clearly very terror of a number, you know now the operation of the mobile phone memory about 6 g, removal of system memory, true to the game to use most is 4 g `, redistribution to GPU | even less memory, and if the memory is being used to a lot of loading map is obviously not acceptable. At the same time, the amount of data the image load will also be given to memory

Based on the above the original texture of inclusions and memory problems, you need to take some compression strategy according to different situations, because I almost no art skills, so the compression format with all kinds of art effect is not very understanding, mainly from the Angle of the functional and performance to analyze the various compressed format application scenarios:

  • High quality compression format: RGBA32 as a high fidelity compression format, can greatly ensure the quality of the picture

  • Medium quality compression format: RGBA16 + Dithering sounds like a castration of RGBA32. Simply put, compared to RGBA32, it has a large degree of color subdivision, you can see the ladder, visual performance is not smooth compared to RGB32

  • Low quality compression formats: ETC1+Alpha/PVRTC4 These compression formats are often the most commonly used compression formats for moving segments, which have incomparable performance advantages over other compression formats

Note:

  • In addition to the reduction of loading bandwidth due to different compression logic, we also need to understand the imageETC1,PVRTC4This type of memory does not need to be decompressed, but can be directlyGPUSupported, so it usually has the best performance compared to other compression formats

3. Deselect Read/Write Enabled

This feature is designed to allow game developers to invoke the control of reading and writing images from C# scripts. Obviously, this is done by the CPU, so in order for the CPU to access the data, a copy of the data needs to be backed up in memory for the CPU to access. At the same time for graphics rendering and display, it will be loaded into video memory to provide data for GPU.

If you don’t need to read or write textures, you can disable this option to avoid using extra memory while the game is running

4. Disable redundant Mip maps

Mip Map is similar to model LOD, which is also a technique to change the accuracy of the rendering Map based on the rendering distance. The advantage is that it can save performance when objects are far away from rendering. However, Mip Map can increase memory usage.

The technical principle of Mip map is to generate a set of images with different precision by decreasing the power of 2 of the original image. When the game runs, this set of images is loaded into memory, and images with different precision are used depending on the distance rendered.

How much memory footprint does Mip map increase

  • Before we useMip mapIs assumed to be256X256And will generate8A picture of different accuracy. According to the2Calculate the size of each tile and add up. The resulting image group is probably larger than the original individual map33%

Through an instance to verify, assuming that the original image size is 8 m, generated the first low precision of the size of the picture is 2 m (resolution is reduced by half, the size will become a quarter of the original, is easy to understand) this decline about eight times, and then accumulate, will obtain the size of the final image through a simple recursive method to calculate the:

    public void Awake()
    {
        Debug.Log(GetMipmapSize(8.8) /8);
    }
    ImageSize: initial size returns an increased amount of memory
    float GetMipmapSize(int index,float imageSize)
    {
        float lastSize = 0;
        if (index == 1)
        {
            lastSize = imageSize*0.25 f;
        }
        if (index > 1)
        {
            lastSize = imageSize * 0.25 f + GetMipmapSize(index - 1, imageSize * 0.25 f);
        }
        return lastSize;

    }
Copy the code

Execute the program and get the following result:And you can see that the answer is close to PI33%Of course ifMip MapInstead of processing a texture eight times, the calculation will be biased, but in fact, from three times up, the percentage of memory usage increases very little, and basically stays around33%Modify the above code slightly to make a small verification:

 	public void Awake()
    {
        for (int i = 3; i < 15; i++)
        {
            Debug.Log(string.Format("Processing {0} times memory usage: {1}",i,GetMipmapSize(i, 8) / 8)); }}float GetMipmapSize(int index,float imageSize)
    {
        float lastSize = 0;
        if (index == 1)
        {
            lastSize = imageSize*0.25 f;
        }
        if (index > 1)
        {
            lastSize = imageSize * 0.25 f + GetMipmapSize(index - 1, imageSize * 0.25 f);
        }
        return lastSize;
    }
Copy the code

The resulting log is:It can be found that, from the third floor, basically maintained at33%And as the number of layers increases, the memory footprint increases very, very little.

Unity supports a minimum of 32X32 textures, which means that the smallest textures will also produce three additional layers of low precision textures: 16X16, 4X4, and 1X1. This is why many articles about using Map mIP say it will increase memory usage by about 33%

While Mip maps are a performance optimization technique in and of themselves, textures that do not change rendering accuracy, such as 2D sprites or UI elements, take up extra memory, so remember not to check Mip maps when using textures on 2D sprites or UI elements.

5. Pack an atlas

The main purpose of gallery packaging is to optimize the number of Draw calls during UI graphics rendering. The basic principle is also to reduce Draw calls through the batch of UI elements, and to improve CPU performance. For details, please refer to my previous article:

Atlas package article:

  • Unity packs Sprite into an atlas

] (blog.csdn.net/xinzhilinge…).

Second, the model

The performance of the model depends more on the art specification than on the texture. There is not much that can be optimized programmatically, but there are a number of options in Unity that affect the performance of the model loading, rendering, etc. We can see this when importing: Enable Reader/Write Enables:

Click on the modelInspectorThe palette sees these Settings, similar to textures, that can be disabled if you don’t need to modify the model in the gameReader/Write EnablesTo avoid using extra memory for data backups, you can find this information in the Unity documentation:Translation:

  • With this option enabled, Unity uploates Mesh data to GPU addressable memory, but also stores it in CPU addressable memory. This means Unity can access Mesh data at run time, and it can be accessed from a script.

  • With this option disabled, Unity uploates Mesh data to GPU addressable memory and then removes it from CPU addressable memory

  • By default, this option is disabled. In most cases, to save runtime memory usage, disable this option

As for the model itself, it is necessary to avoid having redundant faces in the model. Especially on mobile. This is because high-precision models have many performance challenges in addition to their own pressures

2, try not to check the function options that are not needed

In Unity, some features consume resources to maintain their state even if you don’t use them. Similar to the Reader/Write Enables option above, you can disable any functions that you can’t use

3. Set some quality and performance options

UnityOptions for optimizing the model are availableUnityRead about them in the official documentation, which is also briefly listed here:As you can see from the picture above, there are several options that affect model performance and game performance:

  • Mesh Compression: Increasing compression reduces the accuracy of the grid by compressing the grid data using grid boundaries and the lower bit depth of each component. In the bestMeshTurn it up as high as possible if it doesn’t look too different from the uncompressed version. This is useful for optimizing the size of your game
  • Optimize Mesh: Determines the order in which triangles are listed in the grid for better resultsGPUPerformance is checked by default
  • Normals: If the mesh model is neither normal map nor affected by real-time lighting, select itNone, which can also improve performance

In fact, Unity has some options for programmatically controlling model quality to change performance, but they are not recommended. It is expected that these options can be used to adjust performance, rather than having the art handle the model directly. After all, they are more professional and can better ensure that the performance of the model and performance of the balance.

4. Use LOD

As for LOD, it should be discussed in the rendering section, but this technique has a lot to do with the model grid, so I will introduce it in advance

LODnamelyLevels of Detail“, which translates as multi-level detail, similar to texture renderingMip mapTechnique is also a technique to set the render accuracy according to the render distance. The way to achieve this is that during game development, the art will make a set of models with different accuracy according to different rendering distances and import them intoUnitythroughLODThe component connects its set of models and sets parameters. So when the game is running, there will be different render accuracy at different distances:

This is an example from Unity’s official documentation, which shows that the render accuracy gradually decreases as the render distance increases until it is removed. The advantage of doing this is to keep the game visually presentable while minimizing the render stress. To put it simply, if LOD is not used, as the distance increases, objects occupy fewer pixels on the screen, and the number of triangles per pixel increases. The render pressure per unit increases. It is obviously unreasonable that rendering pressure is higher where the demand for screen performance is not high. Therefore, LOD is needed to solve such problems.

Of course, this technique also has considerable drawbacks. First of all, it will increase the volume of the package, and also increase the workload of the art. So in a real-world opening, this technique is typically used only for a few important objects

conclusion

Some of the common points about resources affecting game performance described above are the ones that game developers are most exposed to on a daily basis, and the deeper, lower-level ones need to be tailored to the characteristics of the project.