I needed to create a hook into a class I’m working on that will return a GameObject for a given index. Now, I could have just built that function into my class, but I’d rather make this class re-usable by other projects down the line (and even other classes within the same project).
public System.Func<int,Transform,Transform> rowForRowIndex;
The first two parameters are passed to the function from the calling method, while the third is the returned object. So in this case, I would invoke the function as follows:
row = rowForRowIndex(r,cachedRow);
Where, r is the index of the row I want to generate, and cachedRow is a row object that has been previously created but is free for use.
You can obviously use different parameters & return type than I am, just remember, the last entry is always the return type, so
public System.Func<bool> isValid;
will return a bool and takes no parameters, while
public System.Func<int,float> rootOfInt;
will return a float and take 1 int as a parameter.
You can also use lambdas to create in-line functions using this syntax:
public System.Func<int,float> rootOfInt = (x) => Mathf.Sqrt(x);
While this is similar to System.Action, the big difference is that System.Func can return a value, System.Action is always type Void.