- Home /
Storing functions in a list/array?
Hello!
I am desperatly looking for help! I'm working on RTS game and I want to make an list/array of functions, which the unit would go through in the order and execute the functions one by one. I've been googling and trying to figure this out for almost week now.
Currently I have this:
var unitQueue : List.<Function> = new List.<Function>();
public function Move(location) {
//Move to location
}
and I'm trying to add this function in array with:
unitQueue.Add(Move(location));
This returns me an error:
BCE0017: The best overload for the method 'System.Collections.Generic.List.<Function>.Add(Function)' is not compatible with the argument list '(void)'.
Any ideas, fixes?
Have a look at the $$anonymous$$SDN documentation for Function.
Incidentally, I prefer a wrapper class and delegates to hold "command" arguments. Gives you more room for expansion:
public class GameCommand {
// names, ids, flags, types can go here
// along with a delegate or battery of delegates
// and helper methods
}
Answer by Tomer-Barkan · Apr 12, 2015 at 07:11 AM
That's the incorrect syntax to create a dynamic function in javascript. What you do is actually call Move(location), and put the result inside the queue.
If you want to put the function call itself, you need to create a dynamic function:
Javascript:
unitQueue.Add(function () { Move(location); });
C#:
List<System.Action> unitQueue = new List<System.Action>();
unitQueue.Add(() => Move(location));
Here's some reading material about lambda expressions in Javascript: http://www.i-programmer.info/programming/javascript/1031-javascript-jems-lambda-expressions.html
How do I then call the function? Would it be something like this?
unitQueue[0];
Each array element is a function, so you would call it as you would call any function:
unitQueue[0]();
Thanks alot! Finally got everything to work after messing with this for a week!