繁体   English   中英

Unity C#列表内存泄漏

[英]Unity c# List memory leak

在运行时分配纹理时,我遇到了严重的内存泄漏。

当useNewArray为true时,任务管理器显示Unity的内存使用量以每秒20 MB的速度增长。

完整的(183k压缩)项目可以在这里下载: https ://goo.gl/axFJDs

这是我的代码:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class testMemory : MonoBehaviour {

public bool             useNewList = false;
Texture2D               newTexture;
public byte             color;
List<Color>             newColors;
List<byte>              staticPixelColorsList;
Color                   tempColor = Color.white;

// Use this for initialization
void Start () {

    newTexture = new Texture2D(0,0);
    newColors = new List<Color>();
    staticPixelColorsList = new List<byte>(120000);
    GetComponent<Renderer>().material.mainTexture = newTexture;
}

// Update is called once per frame
void Update () {

    // Make sure we're using different colors for every frame
    color = (byte)((Time.time*255) % 255);

    if(useNewList)
    {
        // This option causes a memory leak, but it's the one I need 
        // because I'm getting the texture data from an external source
        int newWidth  = Random.Range(200,400);
        int newHeight = Random.Range(200,400);

        // Create a new list each time
        List<byte> newPixels = new List<byte>(newWidth * newHeight);
        for(int i = 0; i < newWidth * newHeight; i++)
        {
            newPixels.Add ((byte)(color * i / 120000f));
        }
        setTexture(newPixels, newWidth, newHeight);

        // Clear the list (yeah, right)
        newPixels.Clear ();
    }
    else
    {
        // Use the same list, but assign new colors
        for(int i = 0; i < 120000; i++)
        {
            staticPixelColorsList.Add ((byte)(color * i / 120000f));
        }
        setTexture(staticPixelColorsList, 300, 400);
        staticPixelColorsList.Clear ();
    }
}

void setTexture(List<byte> inputPixels, int inputWidth, int inputHeight)
{
    newTexture.Resize(inputWidth, inputHeight);

    float colorValue;

    // Convert input value to Unity's "Color"
    for(int n = 0; n < newTexture.width * newTexture.height ; n++)
    {
        colorValue = inputPixels[n] / 255.0f;
        tempColor.r = tempColor.g = tempColor.b = colorValue;
        newColors.Add (tempColor);
    }

    // Actually set the texture pixels
    newTexture.SetPixels(newColors.ToArray());
    newTexture.Apply();
    newColors.Clear();
}
}

提前感谢。

根据此MSDN文章List<T>.Clear方法将Count属性重置为0,并释放对集合元素的所有引用。

但是,容量保持不变。 因此,相同数量的内存保持分配状态。 要释放此内存,应调用TrimExcess方法或手动设置Capacity属性。

也许不必在每次调用Update方法时都创建新的newPixels列表,而是可以在函数外部(可能在类声明中)创建此列表,并在每次调用Update方法时重新填充它? 清除将是可选的,因为每次调用都会覆盖其内容。 这也可以提高性能,因为您的代码不必在每次更新结束时释放集合的每个成员。

显然,这是Texture2D.Apply()的错误。 它是如此之深,Unity的探查器没有显示泄漏,但是外部工具显示了泄漏。 Unity已经意识到了这个问题,并正在寻找解决方案。 没有给出日期。 谢谢您的帮助 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM