Unity particleSystem main access cannot modify struct member when accessed struct is not classified as a variable

Viewed 118

I have the following code to modify a property of the ParticleSystem in Unity

waterCone.main.loop = true;

However, this is giving me the following error

Property 'main' access returns temporary value. Cannot modify struct member when accessed struct is not classified as a variable

Unity's own docs seem to show this code being used as follows

var waterConeMain = waterCone.main;
waterConeMain.loop = true;

With no errors at all.

Why does this fix the problem, as far as my understanding of c# goes, this should be the exact same.

In fact, as far as I can tell neither should work.

I tried to compare the two in Sharplab but the first would not even compile.

What's going on here? And why is this variable necessary?


(edit)

From looking into the source code, it looks like ParticleSystem.main is doing this

MainModule main => new MainModule(this);

And Main is a struct, which has loop as a property like

get => ParticleSystem.MainModule.get_loop_Injected(ref this);
set => ParticleSystem.MainModule.set_loop_Injected(ref this, value);

But really this seems to leave me with more questions than answers, why is this a compilation error when I don't use a temporary variable?

1 Answers

The return type of ParticleSystem.main is a struct type, you cannot directly modify its value. The main reason why you can't do this is that the returned struct value is just a copy, so it's usually meaningless to modify the value at this time and it will cause some imperceptible errors. Quote the explanation from official document

This error occurs because value types are copied on assignment. When you retrieve a value type from a property or indexer, you are getting a copy of the object, not a reference to the object itself. The copy that is returned is not stored by the property or indexer because they are actually methods, not storage locations (variables). You must store the copy into a variable that you declare before you can modify it.

Related