Unity3d c# - Vector3 as default parameter

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.


I know this is already answered but I just want to add other ways to do this. Vector3? p and Vector3 bar = default(Vector3) should do it.

public void SpawnCube(Vector3? p = null)
{
    if (p == null)
    {
        p = Vector3.zero; //Set your default value here (0,0,0)
    }

}

As htmlcoderexe pointed out,

To use p, you have to use p.Value or cast the p back to Vector3 with ((Vector3)p).

For example, to access the x value from this function with the p variable, p.Value.x, or ((Vector3)p).x.


OR

public void SpawnCube(Vector3 bar = default(Vector3))
{
    //it will make default value to be 0,0,0
}

Hi I just ran into this issue where I needed the Vector3 to be optional. But it would keep saying i need a compile time constant. To get around this issue I used this :

    public void myMethod(Vector3 optionalVector3 = new Vector3())
    {
        //you method code here...
    }