In Unity projects featuring explosions you often do this
private Dictionary<string, System.Action> explosions;
void .. initialize in your class constructor .. ()
{
explosions = new Dictionary<string, System.Action>();
explosions.Add("huge", SomeCall);
explosions.Add("huger", SomeCall);
etc
}
No problem, but it would make me happy if you could do this...
private Dictionary<string, System.Action> explosions =
new Dictionary<string, System.Action>()
{
{"huge", SomeCall},
{"huge", SomeCall},
etc
};
That would make me much happier ... you know that feeling when you sleep better, enjoy meals with more of a smile?
Of course, that doesn't work because:
Assets/scripts/objects/flite groups/ReallyTremendousExplosions.cs(134,26): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `ReallyTremendousExplosions.SomeCall()'
Can anyone bring me peace on this?
Is there a way to get around the fact that you have to do it at initialization time?
I love dictionary initializers and I use them all the time. I feel your tears.
The answer is in your question, use a delegate!
public class ReallyTremendousExplosions
{
private delegate void ExplosionFactory(ReallyTremendousExplosions source);
private Dictionary<string, ExplosionFactory> Explosions = new Dictionary<string, ExplosionFactory>()
{
{ "huge", x => x.SomeMethod() },
{ "huger", x => x.SomeMethod() }
};
private void SomeMethod()
{
//Render massive explosions...
}
public void RenderNamedExplosion(string explosionName) {
ExplosionsFactory explosionFactory;
if (!Explosions.TryGet(explosionName, out explosionFactory) {
throw new NoSuchExplosionException(explosionName);
}
explosionFactory(this);
}
}
Code fully tested in Unity5/Mono.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With