简体   繁体   中英

Unity3d c# - Vector3 as default parameter

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) .

I know this is already answered but I just want to add other ways to do this. Vector3? p 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
}

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.

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...
    }

As a workaround You can overload method.

INSTEAD THIS

void SpawnCube(Vector3 p = new Vector3(0,0,0)){...}

USE THIS

void SpawnCube(Vector3 p)
{
  //Implementation
}

//overloaded method without parameter which calls SpawnCube with given default parameter
void SpawnCube()
{
  SpawnCube(new Vector3(0,0,0));
}

You've got one implementation of SpawnCube method body and you can use it with or without parameter :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM