How can I pass an external instance to the constructor of an object that's being created using the default XNA XML content loader?
Posted
by
Michael
on Game Development
See other posts from Game Development
or by Michael
Published on 2011-06-29T21:39:56Z
Indexed on
2011/06/30
0:31 UTC
Read the original article
Hit count: 261
I'm trying to understand how to use the XNA XML content importer to instantiate non-trivial objects that are more than a collection of basic properties (e.g., a class that inherits from DrawableGameObject
or GameObject
and requires other things to be passed into its constructor).
Is it possible to pass existing external instances (e.g., an instance of the current Game
) to the constructor of an object that's being created using the default XNA XML content loader?
For example, imagine that I have the following class, inheriting from DrawableGameComponent
:
public class Character : DrawableGameComponent
{
public string Name { get; set; }
public Character(Game game) : base(game) { }
public override void Update(GameTime gameTime) { }
public override void Draw(GameTime gameTime) { }
}
If I had a simple class that did not need other parameters in its constructor (i.e., the Game
instance), then I could simply use this XML:
<XnaContent>
<Asset Type="MyNamespace.Character">
<Name>John Doe</Name>
</Asset>
</XnaContent>
...and then create an instance of Character
using this code:
var character = Content.Load<Character>("MyXmlAssetName");
But that won't work because I need to pass the need to pass the Game
into the constructor.
What's the best way to handle this situation? Is there a way to pass in things like the current Game
using the default XNA XML content loader? Do I need to write my own XML loader? (If so, how?) Is there a better object-oriented design that I should be using for my classes?
Note: Although I used Game
in this example, I'm really just asking how to pass any type of existing instance to my constructors. (For example, I'm using the Farseer Physics Engine, and some of my classes also need a reference to the Farseer World
object too.)
Thanks in advance.
© Game Development or respective owner