You can use the params keyword in the argument list of a method in C#. It can accept one or more parameters of a type that you specify. In the example below you can specify no string parameter, or one or more string parameters. The params keyword has been around since .NET 1.0 if I’m not mistaken and works fine in Mono.
private void ParamsMethod(params string[] list)
{
for (int i = 0; i < list.Length; i++)
Debug.Log(list*);*
I’m not so sure you can have optional parameters, but you can have different functions with the same name, different parameter lists, so you can have one with and one without, and have one call the other with the ‘optional’ parameter.
Optional parameters are a C# 4.0 feature. The latest version of Mono is 2.8, which does actually support C# 4.0, but Unity is using Mono 2.6. See this question which deals with this topic:
It’s from january, but I think it’s still valid. That version of Mono doesn’t have all of C# 4.0 implemented yet and is mostly still C# 3.5. So you’re going to have to wait a while longer for Optional Parameters (and Named Parameters, for that matter).
Unity can use optional parameters in Unity 3. Also, named parameters work too.
Perhaps you should explain what “doesn’t work” and what the errors actually are. Also, it’s much better if you post code that people can test easily without having to reproduce a bunch of external dependencies. For example, this works fine:
using UnityEngine;
public class Test : MonoBehaviour {
void Start () {
Foo();
Foo("bye");
}
void Foo (string testString = "hi") {
Debug.Log (testString);
}
}
Keep in mind that JS does not currently support optional parameters. This means you can’t use optional parameters if you’re writing code that you intend to distribute and be used by other users in general, such as utilities. If your code is only going to be used by you, or if you specifically intend to restrict it to C# users only, then go ahead.
You can use optional parameters in C#.
– Eric5h5