using UnityEngine;
public class temp : MonoBehaviour {
public delegate void Operation();
public void methodA(int integer){
Debug.Log("method A: "+integer);
}
public void methodB(string word){
Debug.Log("method B: "+word);
}
public static Operation CreateOperation(Operation iteration, int repetitions){
return delegate() { //or Lambda expression: return () => {
int count = repetitions;
Operation method = iteration;
for(int i = 0; i<count; i++) method();
};
}
public static Operation CreateOperation(params System.Action[] iterations){
return delegate() {
System.Action[] actions = iterations;
foreach(System.Action action in actions) action.Invoke();
};
}
void Start(){
//Operation by Anonimous method
Operation methodsGroup1 = CreateOperation (() => methodA(1),() => methodB("word"));
Operation methodsGroup2 = CreateOperation (() => methodA(10),5);
methodsGroup1();
methodsGroup2();
}
}
I’ve managed to create methods group using the generic delegate Operation and lambda functions.
But I would like to add methods as argument, without using lambda functions, amb use indeterminate number of parameters as does StartCoroutine of Unity.
This is useful to create and modify code at runtime.
You are miss understanding how StartCoroutine works it isn’t taking a function with arguments as a arg but the return of that function which is of the type IEnumerator.
What you want yo do isn’t really possible without lambda, or using delegates. Though you can use delegates with generics to make them work for multiple arugmeant types.
Unless your using a dynamically typed language like python what you want can’t be done in the way you want.
No problem, you can convert methods from void to IEnumerator and add yield instruction.
Do you know as StartCoroutine works? Please send example with IEnumerator methods or complete CreateAction method from next code to return System.Action:
using UnityEngine;
using System.Collections;
public class temp : MonoBehaviour {
public IEnumerator myMethod1(string str){
Debug.Log("method1");
yield return null;
}
public IEnumerator myMethod2(float number,string str,bool active){
Debug.Log("method2");
yield return null;
}
public System.Action CreateAction(params IEnumerator[] methodsArray){
return () =>{
IEnumerator[] methods = methodsArray;
foreach(IEnumerator method in methods){
//How to invoke the method with the same arguments values
//as StartCoroutine?
}
};
}
void Start(){
System.Action methodGroup = CreateAction(myMethod1("one"),myMethod2(1f,"two",true));
methodGroup();
}
}
I look at example about delegate with params object[ ] args to indeterminate number of parameter, but need pass all arguments as object, and need pass delegate to method and object[ ] args array by separate.