Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have tears because I don't know how to field initialize a Dictionary with Action?

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?

like image 861
Fattie Avatar asked Nov 16 '25 19:11

Fattie


1 Answers

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.

like image 133
Tewr Avatar answered Nov 18 '25 08:11

Tewr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!