How can we add Vector3
as default parameter for a method? for example:
Void SpawnCube(Vector3 p = new Vector3(0,0,0)){...}
I just tried the line about I got an error:
Expression being assigned to optional parameter `p' must be a constant or default value
I want to customise a function to spawn some game objects
that if I did not provide the transform.position
, it will go to (0,0,0)
.
In the general case, you can't. The default arguments are somewhat limited. See this MSDN page.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:
a constant expression;
an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
an expression of the form default(ValType), where ValType is a value type.
In the specific case you posted however, I suspect that new Vector3()
will be equivelent to new Vector3(0,0,0)
, so you may be able to use that instead.
If you need a non-zero default value, you may be able to use method overloading instead.