Struct field initializers

In the current Unity build, which I’m on 2023.3.0b6 there is no way to initialize my defined variables inside a structure?

[Serializable]
  public struct SomeHeader
  {
      public float _speed = 1.0f;
  }

It’s complaining about c#10 and if I’m not mistaken, the current build is 9.0? .net 2.1 ?

No work around for initializing these variables for the inspector ? I read earlier something about Unity’s own branded version of c#… So I’m assuming updating the runtimes on our own is out of the question?

You can do it inside of the constructor.

struct Employee {

  public int id;

  // constructor
  public Employee() {
   id = 123;
  }
}
1 Like

Thanks!

1 Like

Hmmm?

Nvm, sorry. :slight_smile:

1 Like

Hello, sorry to revive the thread, but I have the same problem. It looks like @wildCherri had the same problem I did, but presumably has a solution. What can I do to initialize the struct with the Parameterless Struct Constructors being unavailable in c# 9.0?

As a solution to this I sometimes see structs given an initialise/init method. Not the most elegant method if it’s used on the regular.

Otherwise until the back end is updated to Core CLR, probably not until Unity 7 or so, we’re stuck with C# 9 language features.

I have an older project in 2021.3.17 and I use structs. I was very happy with my implementation. I am guessing you really want to set these values in the Inspector which was not what I wanted.

I have them declared as public readonly struct ExampleStruct

The properties have a public getter and an “init” setter which allowed me to set them as I needed them once when created. Not a great example below and I didn’t have an int and string but maybe this works for you?

Obviously I could pass values into the method but I didn’t need to and I just cobbled this example together.

public ExampleStruct GetExampleStruct()
{
	return new ExampleStruct()
	{
		TestInt = 1,
		TestString = "test"
	};
}

If you’re not using an object initializer to set things up after the fact, a clean way is to define a static readonly instance, like what’s done for float4.zero in Unity Mathematics.

struct MyType
{
    public int Value;

    public static readonly MyType Default = new() { Value = ~0 };
}

Also, you can always use a compiler response file or project compiler arguments to use C# 10.

2 Likes