I’m trying to build a sorta of interface class like this:
public static float simple (float t)
{
return t;
}
public static float quadratic (float t)
{
return t*t;
}
public static float getResult (float a, float b, float t)
{
a + b * simple(t);
}
In another script, I’m calling:
float r = FakeScript.getResult(x, y, t);
Which works. But if I want to extend my interface so that when calling getResult I can also choose wheter to use simple(t) or quadratic(t) without mayor changes on the function’s body, what do I have to do? With some googling I’ve found out that delegates might be the best option, but I couldn’t find any example that might work on my script. Any other suggestion?
“I want to extend my interface so that when calling getResult I can also choose wheter to use simple(t) or quadratic(t) without mayor changes on the function’s body, what do I have to do? With some googling I’ve found out that delegates might be the best option”
I’ve been learning how to use delegates. The syntax isn’t hard, but they can be used in couple of different ways. In this case, you don’t have to use variables or multicasting, just define the type of method signature in your method, and then pass methods with similar signature, then Invoke, or just call the method, both work the same I think. There is no need to use specialized delegates like Func, Action, Predicate etc, you can also define your own using delegate keyword.
void Start ()
{
var resultA = getResult(1,2,3, simple);
Debug.Log("with myDel1: " + resultA);
var resultB = getResult(1,2,3, quadratic);
Debug.Log("with myDel2: " + resultB);
}
public static float simple (float t)
{
return t;
}
public static float quadratic (float t)
{
return t*t;
}
public static float getResult (float a, float b, float t, Func<float,float> myDelegate)
{
return a + b * myDelegate.Invoke(t);
}
If you are wanting to follow SOLID principles, this would violate the “O”.
In essence, the solution proposed in that link appears somewhat simiilar to the strategy pattern. I guess it’s debatable whether it is prefereable to use an interface or a delegate to achieve a similar result.