separating the existence of an enum from its specific contents
I am codin开发者_如何学编程g an Audio Manager for a game engine, and I would like to keep it generic so that different games could use the same engine. Right now I am using a Dictionary<string,SoundEffect>
to store the sounds and the events they are associated with. I would much rather use an Enum
for the Key, for the many benefits it would entail. Right now, someone could AddSound("Explosion", explosionSound)
and another programmer on our team could PlaySound("ExplosionSpelledWrong")
and so forth.
I would like the Audio Manager to reference a "SoundEvent" enum
. My problem is that the contents of this enum are going to be game-specific. Some games might have:
enum SoundEvent {
Explosion,
GameOver
}
another might have
enum SoundEvent {
Jump,
Laser
}
and so on.
Note that I don't need to ever reference the contents of the enum in the Audio Manager, since it is just going to be a key in the dictionary -- the specific SoundEvent will always be specified in the game-specific project.
So how do I keep my engine separate from the game-specific project? I don't want to refer to anything game-specific in the audio manager.
The first thing I thought of was just to make a namespace GameSpecificEnums
that would nonetheless be part of the Engine project and put them in there. However, for making a different game, one would therefore have to alter this part of the Engine project. It wouldn't be a big deal in reality, but it doesn't sit right.
My other thought is to change the Dictionary to Dictionary<int,SoundEffect>
and then have something like this in game-specific code:
static class SoundEvent {
private const int Explosion = 0;
private const int Laser = 1;
// etc.
}
and then call the Audio Manager with things like:
AudioManager.Add(SoundEvent.Explosion, explosionSound);
but this doesn't feel right either, since someone could AudioManager.PlaySound(2112)
Is there another solution?
It sounds like you might want to make AudioManager
generic in the key type. You could do that without any restrictions, or you could try to constrain it to enums. That isn't feasible with "normal" C#, but I have a project called Unconstrained Melody which accomplishes it with IL rewriting. That's probably overkill here - you could always constrain the key type to be a struct
and just expect everyone to use it properly.
Then your PlaySound
method would take a key of type TKey
etc.
精彩评论