- Home /
function arguments list...?
In Unity JS is there any way to get or set the arguments passed to a function?
I’m trying to create an update manager that can trigger a list of attached functions.
So far I've got it working fine as long as the functions it calls don’t require parameters, or at least have a predetermined number of parameters passed in.
Would I be able to add an arguments array to callIt. eg: callIt.arguments[]=[1,2,3];
// CODE ---------------------------------------------------
var IntroUpdates:UpdateEngine;
function Start(){
IntroUpdates=new UpdateEngine() as UpdateEngine;
IntroUpdates.AddObject(test);
IntroUpdates.UpdateAll();
}
class UpdateEngine{
var updateHash: Hashtable;
function UpdateEngine(){
updateHash = new Hashtable();
}
function AddObject(functionPointer):void{
updateHash.Add(functionPointer, functionPointer);
}
function removeItem(removeKey):void{
updateHash.Remove(removeKey);
}
function UpdateAll():void{
for (var item in updateHash.Keys){
var callIt : Function=item as Function;
callIt();
}
}
}
function test(){
Debug.Log("test triggered");
}
$$anonymous$$aybe this will help.
http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_JavaScript
Trouble is "arguments" is not recognised by Unity.
Does anyone know of an equivalent?
Answer by billybobsmojo · Sep 04, 2011 at 09:53 AM
Looks like there is no equivalent to arguments. Although I have hit upon an alternative. Simply by knowing how many arguments I want to pass to a function enables me to modify how I call it.
If there's only one argument, only pass one. If two, channel to a different statement that specifically sends two. It's a little awkward but achieves the desired result:
if(functionParams.length==0){
callIt();
}else if(functionParams.length==1){
callIt(functionParams[0]);
}else if(functionParams.length==2){
callIt(functionParams[0],functionParams[1]);
}
Answer by Peter G · Sep 04, 2011 at 12:35 PM
In C#, you can use the params
keyword to create a variable number of parameters. Unfortuneately is doesn't work in js, but you might consider writing your trigger script in C#, then calling it from js.
public void Trigger(Collider col, params int[] list) {
//do stuff
for(int i = 0; i < list.Length ; i++ ) {
Debug.Log(list[i]);
}
}
Trigger( someTrigger , 1 ,3, 4, 8);
//pass 4 arguments to the list
Trigger( someTrigger , 1 , 2, 0);
//pass 3 arguments to the list
Trigger( someTrigger )
//list is empty
Trigger( someTrigger , new int[] {1 , 3, 5} );
//you can also pass an array of a matching type to the list.
MSND page on params