2015-05-18 154 views
1

我們如何添加Vector3作爲方法的默認參數?例如:Unity3d c# - Vector3作爲默認參數

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

我只是想行約我得到了一個錯誤:

Expression being assigned to optional parameter `p' must be a constant or default value

我想自定義一個函數來產卵一些game objects,如果我沒有提供transform.position,它會去到(0,0,0)

回答

5

你不能。默認參數是有限的。見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.

然而,在您發佈的具體情況,我懷疑new Vector3()將equivelent到new Vector3(0,0,0),所以你可能能夠使用來代替。

如果您需要一個非零的默認值,您可以使用method overloading來代替。

+0

any any alternative? – sooon

2

我知道這已經回答了,但我只是想添加其他方法來做到這一點。 Vector3? pVector3 bar = default(Vector3)應該這樣做。

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

} 

由於htmlcoderexe指出,

要使用p,你必須使用p.Value((Vector3)p)p回到Vector3

例如,要從p變量,p.Value.x((Vector3)p).x訪問此函數的值x


OR

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

這是否意味着如果我沒有放入任何值,它會轉到'Vector3(0,0,0)'? – sooon

+0

是的。用debug.log自己嘗試一下,然後調用該函數而不傳遞任何值。 – Programmer

+0

如果你使用''Vector3?'',你需要轉換它或使用''p.Value'',否則你會得到一個類型錯誤。 – htmlcoderexe

-1

您可以嘗試使用

Vector3 p = Vector3.Zero 
+0

對不起,這甚至沒有編譯。假定編譯時間不變。 – Reasurria

0

您好我只是碰到了這個問題,我需要的Vector3是可選的。但它會一直說我需要一個編譯時間常量。爲了解決這個問題,我用這個:

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