Question about Delegates

Hi everyone,

I’m somewhat new to Unity/ C# and was wondering if anyone could tell if this is achievable:

I’m working on an evolution simulator for a school project and am trying to create an array of delegates, which will return “inputs” from the creatures “cells”; I’m doing this to make them easily accessible from the creature’s controller (sorry for the bad explanation).

From what I’ve seen delegates must have the same parameters as the methods they’re linked to, I was wondering if I could save a method that has some of it’s parameters filled out as a delegate; something like this:

public delegate void Del_Outputs(float output);

public Del_Outputs[] Creature_Net_Outputs;

public void Example()
    {
        Creature_Net_Outputs = new Del_Outputs[10];
        // Save example_method as delegate by filling out that part of it's parameter that doesn't match
        Creature_Net_Outputs[0] = Example_Method(2);
    }

public void Example_Method(int test, float output)
    {
          // Do things
    }

Basically, I fill out the int parameter, meaning that the only parameter left to be defined is the float output one; this matches the delegate type. Sorry for the bad explanation!

Thanks, Jude.

No, not directly.

But you can create a lambda/anonymous delegate that wraps the mismatched method and define your parameter there (there is a laundry list of technicals in relation to what is going on that may or may not impact performance when using lambdas. From extra call stack frames, to various amounts garbage being generated depending on the scope access of the method. For this simple use case though it’s mostly negligible). This can be accomplished as follows:

Creature_Net_Outputs[0] = (f) => Example_Method(2, f);

Note, delegates already act as collections. You can add/remove delegates from them with the += and -= operators:

System.Action foo;
foo += SomeMethod;
foo += SomeOtherMethod;
foo(); //both SomeMethod and SomeOtherMethod get called
foo -= SomeMethod;
foo(); //only SomeOtherMethod gets called
1 Like

Ah I see, thanks lots! I will look into doing that