- Home /
How to set LayerMask's optional parameter value to 'Everything'?
Is it possible to have an optional layermask parameter set to -1, which is the bit representation for "Everything" without having to overload the function?
public static void DoSomething(LayerMask targetMask = -1){
//TODO
}
will give an error: Optional parameter expression of type int' cannot be converted to parameter type
UnityEngine.LayerMask'
.
Debug.Log(default(LayerMask).value.ToString());
prints 0
Iam sorry for asking a kind of unneccesary question, but when it comes to designing code useful and having things not redundant this is a major problem to me.
Thanks in advance.
Answer by JVene · Aug 21, 2018 at 06:41 PM
My primary language is C++, so I must admit my C# knowledge is not as in depth, but from what I do know you can't provide default class values like this.
LayerMask is a class, and though it has a conversion method for automatically converting an integer to the mask, that does not work at compile time in C#, so this code isn't possible as you've given. You have an "out" though.
LayerMask is merely a wrapper around an integer (I would have assumed an unsigned integer, but it doesn't matter). The parameter of your method will have to use an integer, not a LayerMask, as input. For that you can provide a compile time constant default initializer (where you can't with a class), which can be used during runtime to assign or initialize a LayerMask within the function which will convert at runtime. You merely have to switch your thinking from that of a LayerMask parameter to an integer.
Answer by Bunny83 · Aug 21, 2018 at 08:16 PM
No you can't because default parameters need to be compile time constants. They are just syntactic sugar. So if you want it to be optional, just implement an overload like this:
public static void DoSomething()
{
DoSomething(-1);
}