Friday, December 2, 2022
HomeGame Developmenttextures - Why is that this Unity Texture2D reminiscence leak occurring?

textures – Why is that this Unity Texture2D reminiscence leak occurring?


I’ve a script which is loading a photograph from path right into a texture (photoThumbT2D), then rotating it:

                byte[] byteArray = File.ReadAllBytes(path);
            
                UnityEngine.Object.Destroy(photoThumbT2D);
                photoThumbT2D = new Texture2D(0, 0);
                photoThumbT2D.LoadImage(byteArray);
                photoThumbT2D = RotateImage(photoThumbT2D, -90);

The place the RotateImage perform is customized from right here as:

public static Texture2D RotateImage(Texture2D originTexture, float angle) {
        int width = originTexture.width;
        int peak = originTexture.peak;
        float halfHeight = peak * 0.5f;
        float halfWidth = width * 0.5f;

        Color32[] originPixels = originTexture.GetPixels32();
        Color32[] rotatedPixels = originTexture.GetPixels32();

        int oldX;
        int oldY;

        float phi = Mathf.Deg2Rad * angle;
        float cosPhi = Mathf.Cos(phi);
        float sinPhi = Mathf.Sin(phi);
    
        for (int newY = 0; newY < peak; newY++) {
            for (int newX = 0; newX < width; newX++) {
                rotatedPixels[newY * width + newX] = new Color32(0, 0, 0, 0);
                int newXNormToCenter = newX - width / 2;
                int newYNormToCenter = newY - peak / 2;
                oldX = (int)(cosPhi * newXNormToCenter + sinPhi * newYNormToCenter + halfWidth);
                oldY = (int)(-sinPhi * newXNormToCenter + cosPhi * newYNormToCenter + halfHeight);
                bool InsideImageBounds = (oldX > -1) && (oldX < width) && (oldY > -1) && (oldY < peak);

                if (InsideImageBounds) {
                    rotatedPixels[newY * width + newX] = originPixels[oldY * width + oldX];
                }
            }
        }

        Object.DestroyImmediate(originTexture);
    
        Texture2D consequence = new Texture2D(width, peak);
        consequence.SetPixels32(rotatedPixels);
        consequence.Apply();
        return consequence;
    }

Nonetheless, this software of RotateImage is resulting in a reminiscence leak the place the extra instances it runs the extra reminiscence utilization piles up within the profiler.

Is there an accurate technique to clear the textures being created by this? Thanks.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments