Best way to handle texture loading and access across multiple classes in XNA?

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

So I have a simple XNA project going on. Basically the question I have is how to handle texture loading and making sure there is proper access to those textures from other classes?

For example, every tutorial I've seen, as well as what I can tell from the actual logic of XNA, you're supposed to load textures in the LoadContent() method. But let's say I have another class, Level, that needs its own unique set of textures, and within that I create an instance of my Player object, which also needs its own texture, and of course enemies and everything else.

One way I could do it is just to load the textures needed for a particular class in its constructor, but for that I'd need to set up a new content manager or pass the content manager to each constructor, which seems both unwieldy and outside of what was intended.

So when it comes to full-blown projects that aren't little tutorials that use 2 textures, what's the best way to implement loading them?

回答1:

Create as many ContentManager classes as you need.

Each one is self-contained. Within each content manager, resources (eg: textures) are reused - but if you load the same texture in two different content managers, you get two different instances (try to avoid this).

You cannot unload (Dispose() of) individual resources that a ContentManager loads. You can only Unload() the entire content manager (disposing of everything that it loaded). This is likely to factor into any decision about when to create content managers.

You perhaps want to create one ContentManager per level. And then have another ContentManager for handling things that don't need to be unloaded between levels (eg: the things your Player or enemy objects need).

There's nothing wrong with passing instances of ContentManager around, either.

Of course, for simple games, it's often easiest to just use a single ContentManager and not worry about unloading things.



回答2:

The best solution would be to fragment your entities in a way that only those who need a texture will be able to access the ContentManager.

One such way is creating an abstract base class "GameObject" that receives either the Game object or a ContentManager instance in its constructor.

This way you're ensuring that each of these components will have access to the ContentManager.

Another way to expand on this, is to create your own ContentManager that will contain all the logic to load content, and also add things like loading on a worker thread, streaming, etc.

This makes sure that all the logic is concentrated still in 1 place, and you can expand on the retail "ContentManager" to provide other services that are not available.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!