1

I have ScriptA with a lot of void functions:

void methodOne() { 
   some code
}

void methodTwo(int a, int b) {
}

I want to pass to static method of another script. Lets say it scriptB:

ScriptB.staticMethod(methodOne, some, other, primitive, parameters);
ScriptB.staticMethod(methodTwo(a, b), some, other, parameters);

The main Idea of my scripts is that ScriptB will get datas from server and call methods that got from ScriptA to make changes in my game depending on data.

Mr.D
  • 7,353
  • 13
  • 60
  • 119

2 Answers2

6

I am not sure what you are trying to achieve here. But to answer your question, you can pass methods as parameters using delegates. Here is an example:

public class ScriptA
{
    public delegate void MethodOneDelegate(int a, int b);

    public void MethodOne(int a, int b)
    {
        Console.WriteLine(a + b);
    }
}

public static class ScriptB
{
    public static void StaticMethod(ScriptA.MethodOneDelegate function, int a, int b)
    {
        function(a, b);
    }
}

public static void Main()
{
    ScriptA scriptA = new ScriptA();
    ScriptB.StaticMethod(scriptA.MethodOne, 1, 2);
}

There is alternative solutions, you can take a look at System.Func and System.Action.

Hef
  • 116
  • 7
  • How code will distinguish that `MethodOneDelegate` is `MethodOne`s? I thought I need to assign values. – Mr.D Mar 26 '15 at 10:28
  • `MethodOneDelegate` only describes the signature of `MethodOne` (takes two integers and returns void). The method that will be called by `StaticMethod` is provided as a parameter (scriptA.MethodOne). – Hef Mar 26 '15 at 10:36
  • Can I declare delgates inside of `ScriptB`? it will be like template for calling. – Mr.D Mar 26 '15 at 11:59
  • Yes of course `MethodOneDelegate` could be declared in `ScriptB` instead of `ScriptA`. Or anywhere else. – Hef Mar 26 '15 at 13:11
  • Please add links to System.Func and System.Action – Steak Overflow May 25 '16 at 09:40
0

Do you need to start the methods when you put them as parameters? Or do you need the values from those methods?

Either way, you could do two things, either try this or just pass the name of the method as string and in your method check which name has been entered and start that method in your method.

Community
  • 1
  • 1
HoloLady
  • 1,041
  • 1
  • 12
  • 28