简体   繁体   English

绘制脚本占用了内存和CPU

[英]Draw script eating up memory and cpu

I've been using this script to draw lines, and it works, but when I run my game it starts eating up my resources like no one's business. 我一直在使用此脚本来画线,并且可以工作,但是当我运行游戏时,它开始消耗我的资源,而这无人问津。

public static void DrawLine(Vector2 start, Vector2 end, Color color, int width, float alpha, float depth)
{
                                // GraphicsDevice stored in other class
    var texture = new Texture2D(Graphics2D.GraphicsDevice, 1, 1);
    texture.SetData(new[] { color });

    Vector2 edge = end - start;
    float angle = (float)Math.Atan2(edge.Y, edge.X);

    // SpriteBatch stored in other class
    Graphics2D.SpriteBatch.Draw(
        texture,
        new Rectangle(
        (int)start.X,
        (int)start.Y,
        (int)edge.Length(),
        width),
    null,
    Color.White,
    angle,
    new Vector2(0, 0),
    SpriteEffects.None,
    1.0f);
}

Memory and CPU usage begin to spike as soon as lines start being drawn. 一旦绘制线条,内存和CPU使用率就会开始飙升。

一旦开始绘制线条,内存使用率就会飙升。

Any guesses as to why it's doing this? 关于它为什么这样做的任何猜测? Should I even be overly concerned? 我什至应该过分担心吗? Or is this normal for these kinds of operations. 还是这种操作很正常。

As @Norris mentions in the comment, create the texture at Initialize, and reuse it. 正如@Norris在评论中提到的,在Initialize中创建纹理,然后重新使用它。

The reason it's eating up your CPU is because you're creating an entirely new texture from scratch EVERY FRAME. 它耗尽了CPU的原因是因为您要从头开始创建每个帧都全新的纹理。 This is heavy, because you're asking the GPU to reserve memory and power for creating a new texture, using it that single frame, disposing it again, and the next frame you repeat the process. 这很沉重,因为您要让GPU保留内存和电源来创建新纹理,使用单个帧,然后再次对其进行布置,并在下一帧重复该过程。 There is a reason Photoshop has progress bars when doing some changes to large-ish images. 对大尺寸图像进行一些更改时,Photoshop有进度条是有原因的。

Even if it wasn't cpu-intensive, it is bad practise to recreate something every frame, if you don't have to. 即使它不是CPU密集型的,也不是必须的做法,如果不需要,则每帧都要重新创建某些内容。 Always reuse as much as possible. 始终尽可能重复使用。 This goes for all types of applications, but is especially important in game development due to the 60fps draw loop. 这适用于所有类型的应用程序,但由于60fps绘制循环,因此在游戏开发中尤其重要。 About the only objects this does not apply to, are basic value-types such as Ints, Floats, Vector3's, Matricies , etc. Unless of course these values are based on calculations that needs to occur every frame. 唯一不适用于此对象的对象是基本值类型,例如Ints,Floats,Vector3's, Matricies等。当然,除非这些值基于需要在每一帧进行的计算。

To summarise: Always perform as little work as possible to accomplish your intended goal 总结一下:为了完成您的预期目标,总是做尽可能少的工作

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

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