Search code examples
c#xnasubclasstexture2d

XNA: Using Content.Load with a subclass of Texture2D


So I have a subclass of Texture2D called ScrollingBackgroundTexture. I'd like to use it to load a texture with Content.Load<>, but I can't seem to get it to work.

Here's the code in my subclass (as of now, it's just a constructor):

class ScrollingBackgroundTexture : Texture2D {
    public ScrollingBackgroundTexture(GraphicsDevice graphicsDevice, int width, int height) : base(graphicsDevice, width, height) { }
}

And here's the code from my main class that's giving me trouble:

test = Content.Load<ScrollingBackgroundTexture>("near stars");

The error tells me that the file contains a Texture2D, but I'm trying to load it as a ScrollingBackgroundTexture.

I've also tried

test = (ScrollingBackgroundTexture)Content.Load<Texture2D>("near stars");

But that just gives me another error.


Solution

  • I don't think you can do that. Here's why. The size of a Texture2D is X bytes big. The size of a ScrollingBackgroundTexture is X + Y big. The ScrollingBackgroundTexture doesn't know how to load content that is X big becasue it is X + Y big.

    What you'll need to do is create your own custom content type for ScrollingBackgroundTexture. You can find information on how to do that at MSDN.

    If I were you though, I would switch to something with a bit better design that favors composition over inheritance! This will have the added bonus of not forcing you to mess around with the content pipeline.