Search code examples
c#disposemonogametexture2d

MonoGame - Dispose Texture2D


A few days ago I played with the MonoGame Framework. I construct follow class:

public Texture2D Texture2D { get; set; }
public Vector2 Vector2;

public Point(Texture2D texture2D, Vector2 vector2)
{
    Texture2D = texture2D;
    Vector2 = vector2;
}

public void SetX()
{
    if(Vector2.X > -50)
    {
        Vector2.X = Vector2.X-2;
    }
}

Then I created more than 2 objects and added them to a list:

_points.Add(new Models.Point(Content.Load<Texture2D>("Point"), new Vector2(50, 50));

When I dispos one of them, all textures will be disposed. How can I dispose only one of the two objects?


Solution

  • As a general rule the class responsible for disposing something should be the same class that created it. There are exceptions to this rule but generally if it holds true it'll make problems like this a lot easier to reason about.

    In this case specifically, it seems you've misunderstood how textures are normally disposed in MonoGame. There's basically 2 options:

    1. Textures created with the content manager using Content.Load<Texture2D> are disposed by the content manager (in other words, you shouldn't call Dispose on these textures directly)
    2. Textures created by yourself using new Texture2D are your responisibilty to dispose (in this case you should call Dispose directly)

    Another thing to note is that calling Content.Load<Texture2D>("Point") more than once will actually return a reference to the same texture. This is generally considered a good thing because it will only load the texture into memory once.

    If you actually do want the same texture loaded into memory more than once you'll need to handle this yourself. Although, it's rare that you'll want to do this so make sure you understand the implications first.

    To demonstrate the point consider the following code:

    var texture1 = Content.Load<Texture2D>("Point"); // load texture into memory
    var texture2 = Content.Load<Texture2D>("Point"); // get a reference to the same texture
    

    At this point texture1and texture2 will be the same instance. If you change one of them, you're changing both.

    Later on when your game shuts down somewhere deep in the bowels of the Game class the Content manager will Dispose. This is when the texture will be released. You don't need to do this yourself.