- Home /
how to pass a function to a function
I have a function that differs in only one real way for various methods. How it sorts input. For example if you want the lowest 2 points on the face of a object it finds all objects in the face and sorts them by Y. If you want the farthest in an X or Z axis direction it sorts by that.
I would like to pass to the function the sort method to be passed to sort.
so like
int CompareY(int first, int second)
{
....
}
later i'll use that method via
facevertices.sort(CompareY)
the thing is i'd like to be able to do something like
int mymethod(void sortmethod)
{
facevertices.sort(sortmethod)
}
and then be able to pass it compareY or compareZ or compareX as the sort method.
is that possible to pass a function itself?
http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$onoBehaviour.StartCoroutine.html is the only one I know so far with Unity.
There are probably more derived from $$anonymous$$onoBehaviour
for the record, in Unityscript (javascript),
simply use the incredibly useful Function type
not using java, C#
It seems my answer $$anonymous$$AY BE delegates
Func I think is the C# equiv of javascipt Function type but as my comment on the answer suggests. It doesnt seem to be built in to the base monobehavior methods.
i'm not sure if i need to include something besides system.collections and system.collections.generic to access the func declaration.
Answer by iwaldrop · Jan 16, 2013 at 07:36 AM
While you could use a switch to handle the different methods of sorting this is actually a pretty good use case for playing with the Action and Func features of the C# language. Check this out!
http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/
Func doesnt seem to be supported ( i happened apon that googling).
I wanted to do
int sortfunction1(int first, int second)
{
...
}
int sortfunction2(int first,int second)
{
...
}
int otherfunction(func<int,int,int> sortmethod)
{
blah.sort(sortmethod);
}
but
func doesn't seem to actually be allowed. is there something i need to include to be able to use this? (that is to say autocomplete isn't showing it as a option atm).
figured that out finally which is useful for later, but turns out i dont quite need it atm. Really what i need to pass is an Icomparer
i'm going to open a seperate question for that if you could maybe help. thanks for you help with this one though :)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Problem with 3D platform tutorial 2 Answers
Best Language for Unity 0 Answers
Problem with getting a value from a enum 2 Answers
Can be mesh asset saved with an editable parameter? 0 Answers