首页 > 解决方案 > 为什么 Unity 游戏运行的时间越长,帧数就会大幅下降?

问题描述

我正在使用 Unity 2020.3.4f1 为移动设备创建 2D 游戏。

我为游戏创建了一个地图构建器。当我点击播放时,它会生成一堆保存为 json 文件的“地图”。根据游戏运行时的统计菜单,游戏运行时间越长似乎会导致帧速率极慢(200fps -> 2 fps)。

奇怪的是,如果我转到“场景”选项卡并左键单击一个精灵,fps 会立即再次跳回。

截图

该问题似乎与在 Unity 中截屏有关。大凸起发生并且仅在我取消暂停游戏时重置。 在此处输入图像描述

问题

脚本:

private void Awake()
{
    myCamera = gameObject.GetComponent<Camera>();
    instance = this;
    width = 500;
    height = 500;
}

private void OnPostRender()
{
    if(takeScreenShotOnNextFrame)
    {
        takeScreenShotOnNextFrame = false;
        RenderTexture renderTexture = myCamera.targetTexture;

        Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false); 
        Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
        renderResult.ReadPixels(rect, 0, 0);

        float myValue = 0;
        float totalPixels = renderResult.width * renderResult.height;

        for (int i = 0; i < renderResult.width; i++)
        {
            for (int j = 0; j < renderResult.height; j++)
            {
                Color myColor = renderResult.GetPixel(i, j);
                myValue += myColor.r;
                //Debug.Log("Pixel (" + i + "," + j + "): " + myColor.r);
            }
        }

        occlusion = ((myValue / totalPixels) * 100);

        byte[] byteArray = renderResult.EncodeToPNG();

        System.IO.File.WriteAllBytes(Application.dataPath + "/Resources/ScreenShots/CameraScreenshot.png", byteArray);

        // Cleanup
        RenderTexture.ReleaseTemporary(renderTexture);
        myCamera.targetTexture = null;
        renderResult = null;
    }
}

private void TakeScreenshot(int screenWidth, int screenHeight)
{
    width = screenWidth;
    height = screenHeight;

    if(myCamera.targetTexture != null)
    {
        RenderTexture.ReleaseTemporary(myCamera.targetTexture);
        //Debug.Log("Camera target texture null: " + myCamera.targetTexture == null);
    }

    myCamera.targetTexture = RenderTexture.GetTemporary(width, height, 16);
    takeScreenShotOnNextFrame = true;
}

public static void TakeScreenshot_Static(int screenWidth, int screenHeight)
{
    instance.TakeScreenshot(screenWidth, screenHeight);
}

}

标签: c#unity3d

解决方案


推荐阅读