可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.