0

I got this error when update my project and run the Api Updater of unity3d:

Optional parameters must appear after all required parameters

Any idea what's wrong with this code?

public static Transform AddChild(this Transform tfm, string name = "", 
    [Optional] Vector3 offset)
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Scott Blank
  • 39
  • 2
  • 4
  • 1
    Got **what** error? – Wyck Jun 14 '19 at 18:04
  • 1
    The error is referring to `string name = ""` being an optional parameter. Take a look at [this question](https://stackoverflow.com/questions/40171095/use-optional-defaultparametervalue-attribute-or-not). – itsme86 Jun 14 '19 at 18:04
  • 1
    Where did you get the idea to use [Optional] in C#? – Steve Jun 14 '19 at 18:06
  • 1
    :facepalm: * I see what you did now. The error text is the title of the question. And "this error" refers to the title. That's a little unusual for Stack Overflow, I think. Better to post the error text into the body of your question. It's a tiny bit confusing. – Wyck Jun 14 '19 at 18:16
  • Similar question: [Does optional parameter and optional attribute not supported together?](https://stackoverflow.com/q/25095627/150605). @JonathonChase The [`OptionalAttribute` class](https://learn.microsoft.com/dotnet/api/system.runtime.interopservices.optionalattribute) is for [COM interop](https://learn.microsoft.com/dotnet/framework/interop/applying-interop-attributes). – Lance U. Matthews Jun 14 '19 at 18:55

2 Answers2

1

If you want the last parameter being optional give it a default value as well

public static Transform AddChild(this Transform tfm, string name = "", Vector3 offset = default)

see c# - Optional Parameters for more information.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • The docs list `Vector3.zero` as a static property, not a constant. If that's correct then I don't think C# will let you use it as an optional default. `default(Vector3)` or just the shorthand `default` should mean the same thing, though. – StriplingWarrior Jun 14 '19 at 18:24
  • yes right it has to be `default` or `new Vector3()` – derHugo Jun 14 '19 at 18:26
1

It looks like you want offset to be an optional parameter. To do this, you'll need to decide what an appropriate default value would be if someone doesn't provide it in their method call. If you've got logic that treats no offset as a special case, I'd suggest making it nullable.

public static Transform AddChild(this Transform tfm, string name = "", Vector3? offset = null)

If not providing an offset means that the offset is zero (putting this transform in the same place as its parent), then set it to default.

public static Transform AddChild(this Transform tfm, string name = "", Vector3 offset = default)
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315