Sign in to follow this  
Arania

Factory-Like functionality in XNA

Recommended Posts

This is probably going to sound like a weird question, but here goes-

I've been playing around with a game idea in XNA for the last couple of weeks, and in order to keep the code maintainable, I want to try and keep individual in-game object code defined in seperate code files.
For the core game objects (like a ship or a projectile), this isn't too much of a problem, but I want to modularize visual effects code ('visual effects' in this case meaning like an explosion or a flash) in a similar manner.

The main problem I'm running into with this is that there's 15+ different visual effects, and I need to be able to pick which effect to instantiate based on the contents of a string passed during execution.
The only method i've managed to come up with myself is to have a static class to act as a 'factory' of sorts, with a large switch statement inside that picks which effect class to instantiate. However, this seems like a somewhat cumbersome solution, and it would require me to add another case for each effect class I add in.

Is there any way that I could create the desired class directly, without having to hard-code the relationships? I've heard of using activator.createinstance for something similar to this, but i'm hesitant to use it as i'm not sure what sort of processing overhead that method has (what little info I could find on it suggested it was very slow).

Share this post


Link to post
Share on other sites
Set up a table mapping your string to a visual effect factory that takes care of creating the right one. So as a quick example:

[source lang="csharp"]
interface IVisualEffect
{
...
}

interface IVisualEffectFactory
{
IVisualEffect Create();
}

Dictionary<string, IVisualEffectFactory> factoryTable;
var effect = factoryTable["ScreenFlash"].Create();
[/source]

There are plenty of ways to enhance this, such as using System.Type instead of a string for better type safety and faster lookups. Additionally, you could mark your Factories with an attribute that denotes the type they create, and then use reflection to automatically build the table.

Share this post


Link to post
Share on other sites
I think that you should see this example:[url="http://create.msdn.com/en-US/education/catalog/sample/particle_3d"]http://create.msdn.com/en-US/education/catalog/sample/particle_3d[/url]

Look at particles settings and how they are used.

Good luck!!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this