如何在Unity中释放内存?

阿列克谢·季莫申科

我看到当我在 Unity 中的每帧(30fps)上创建网格和纹理时,感觉 Unity 在使用后不会从内存中释放这些数据。

有我的代码

private bool UpdateFrame(int frameIdx)
    {
        bool result = true;
        int readyBuffSize = DecoderAPI.stream_get_ready_buffer_size(m_stream);

        if (m_currMeshFrameIndex != frameIdx
            && readyBuffSize > 0)
        {
            m_currMeshFrameIndex = frameIdx;

            IntPtr frame = DecoderAPI.stream_get_next_frame_obj(m_stream);

            if (frame == IntPtr.Zero)
            {
                result = false;
            }
            else
            {
                long sequentialFrameIdx = DecoderAPI.get_sequential_number(frame);
                DebugMethod("UNITY UpdateFrame", $"readyBuffSize :: {readyBuffSize}");
                DebugMethod("UNITY UpdateFrame", $"sequentialFrameIdx :: {sequentialFrameIdx}");

                Mesh releaseFormer = m_meshFilter.mesh;
                m_meshFilter.mesh = CrteateMesh(frame);
                Texture2D texture = CreateTexture(frame);
                m_meshRenderer.material.SetTexture("_MainTex", texture);

                DecoderAPI.stream_release_frame_obj(m_stream, frame);
                Destroy(releaseFormer);  // does not seem to help: even when there are no more allocations in C++ the process grows endlessly
            }
        }

        return result;
    }

private Mesh CrteateMesh(IntPtr frame)
    {
        Mesh mesh = new Mesh();

        //Vertices***
        int vertexCount = DecoderAPI.frame_get_vertex_count(frame);
        byte[] xyzBytes = new byte[vertexCount * 3 * 4];
        IntPtr xyz = DecoderAPI.frame_get_vertex_xyz(frame);
        Vector3[] vertices = new Vector3[vertexCount];

        GCHandle handle = GCHandle.Alloc(vertices, GCHandleType.Pinned);
        IntPtr pointer = handle.AddrOfPinnedObject();
        Marshal.Copy(xyz, xyzBytes, 0, xyzBytes.Length);
        Marshal.Copy(xyzBytes, 0, pointer, xyzBytes.Length);
        handle.Free();

        mesh.vertices = vertices;
        //***

        //Faces***
        int faceCount = DecoderAPI.frame_face_count(frame);
        int trisArrSize = faceCount * 3;
        int[] tris = new int[trisArrSize];
        IntPtr indices = DecoderAPI.frame_face_indices(frame);
        Marshal.Copy(indices, tris, 0, trisArrSize);
        mesh.triangles = tris;
        //***

        mesh.RecalculateNormals();

        //UV***
        int uvCount = DecoderAPI.frame_get_uv_count(frame);
        IntPtr uvData = DecoderAPI.frame_get_uv_data(frame);
        int uvArrSize = uvCount * 2;
        float[] uvArr = new float[uvArrSize];
        Vector2[] uv = new Vector2[uvCount];
        Marshal.Copy(uvData, uvArr, 0, uvArrSize);

        for (int i = 0; i < uvCount; i++)
        {
            Vector2 result = new Vector2(uvArr[i * 2], uvArr[i * 2 + 1]) * new Vector2(1, -1);
            uv[i] = result;
        }

        mesh.uv = uv;
        //***

        if (vertexCount != uvCount)
        {
            long frameId = DecoderAPI.get_sequential_number(frame);
            DebugMethod("UNITY CrteateMesh", $"HERE : in frame id :: {frameId}, vertexCount : {vertexCount}, uvCount : {uvCount}");
        }

        return mesh;
    }

private Texture2D CreateTexture(IntPtr frame)
    {
        IntPtr textureObj = DecoderAPI.frame_get_texture_obj(frame);
        DecoderAPI.TextureInfo textureInfo = DecoderAPI.texture_get_info(textureObj);

        int width = textureInfo.width;
        int height = textureInfo.height;
        int channels = textureInfo.channels;
        int stride = textureInfo.stride;

        //DecoderAPI.ColorType colorType = textureInfo.color_type;

        IntPtr pixels = textureInfo.pixels;
        Texture2D texture = new Texture2D(width, height, TextureFormat.RGB24, false);
        //Texture2D texture = new Texture2D(width, height, TextureFormat.DXT5, false);
        texture.LoadRawTextureData(pixels, width * channels * height);
        texture.Apply();

        return texture;
    }

所以,我所做的是 - 我为每一帧使用它创建一个网格和纹理,然后我希望 Unity 应该在使用后从内存中释放它们,但没有。好的,我发现这种方法Destroy(releaseFormer)应该会有所帮助,但无论如何,我在 TaskManager 中看到的内存无休止地增长是一样的......

为了测试,我已经尝试过 -> 我开始我的 C++ 代码生成(假设 100 帧)然后我停止它(所以我的 C++ 没有分配任何东西),我仍然看到内存增长到最后。我期望的是 - 好吧,即使 Unity 不释放我不需要的数据,我加载了 100 帧就是这样,为什么内存继续增长?

问题是 - 如何从内存中释放我不需要的所有帧?

编辑

我已经改变了这个方法,Destroy以正确的顺序添加

private bool UpdateFrame(int frameIdx)
    {
        bool result = true;
        int readyBuffSize = -1;

        if (m_stream != IntPtr.Zero)
        {
            readyBuffSize = DecoderAPI.stream_get_ready_buffer_size(m_stream);
        }

        if (m_currMeshFrameIndex != frameIdx
            && readyBuffSize > 0)
        {
            m_currMeshFrameIndex = frameIdx;

            IntPtr frame = DecoderAPI.stream_get_next_frame_obj(m_stream);

            if (frame == IntPtr.Zero)
            {
                result = false;
            }
            else
            {
                long sequentialFrameIdx = DecoderAPI.frame_get_sequential_number(frame);
                DebugMethod("UNITY UpdateFrame", $"readyBuffSize :: {readyBuffSize}");
                DebugMethod("UNITY UpdateFrame", $"sequentialFrameIdx :: {sequentialFrameIdx}");

                if (m_meshFilter.mesh != null)
                {
                    Destroy(m_meshFilter.mesh);
                }

                m_meshFilter.mesh = CrteateMesh(frame);

                if (m_texture != null)
                {
                    Destroy(m_texture);
                }

                m_texture = CreateTexture(frame);
                m_meshRenderer.material.SetTexture("_MainTex", m_texture);

                if (m_stream != IntPtr.Zero)
                {
                    DecoderAPI.stream_release_frame_obj(m_stream, frame);
                }
            }
        }

        return result;
    }
本·彼得森

releaseFormer 是网格吗?您是否尝试在纹理对象本身上调用 Destroy?

另一个线程建议 Resources.UnloadUnusedAssets()

就我个人而言,我会尝试使用 RenderTexture 来执行此操作,尤其是在纹理大小不会经常更改的情况下,尽管可能不适用于您的用例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章