how can i declare function parameters as optional? something like:
function foo(required:String, optional:float = 1.0) {
...
}
how can i declare function parameters as optional? something like:
function foo(required:String, optional:float = 1.0) {
...
}
Unity's Javascript doesn't support optional parameters directly (and neither does C#), but it does support function overloading, so the correct way to achieve this is to define the function twice, once with both parameters, and once with just one parameter. You can then optionally have the single-parameter implementation just pass the default value through to the two-parameter implementation, like this:
function foo(str : String) {
// pass 1.0 as the default value for 'num'
foo(str, 1.0);
}
function foo(str : String, num : float) {
Debug.Log(str + " : " + num);
}
And it might be worth adding that this is equally applicable when working in C# too, where it would look very similar:
private void foo(string str) {
// pass 1.0 as the default value for 'num'
foo(str, 1.0f);
}
private void foo(string str, float num) {
Debug.Log(str + " : " + num);
}
As of Unity 3.1, default arguments are supported in C#. See MSDN for documentation on how they work. Note that Mono Develop doesn't like them, so if you're using the debugger you need to select Tools > Preferences > Unity > Debugger and turn off "Build project in MonoDevelop".
Here's another way, in C# only as far as I know.
public void foo(required:String, params Object[] optionalArgs) {
Debug.Log(optionalArgs.Length);
}
Here is a good explanation: http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions. I hope it works in Unity as well!