Argon Assault - Deactivating Particle System question

Hi, I don’t really have a problem with the lecture but I have a query about the code.


Why does this work:

[SerializeField] GameObject Weapon;
void SetWeaponActive(bool active)
    {
        var emmisionMod = Weapon.GetComponent<ParticleSystem>().emission;
        emmisionMod.enabled = active;
    }

While this throws an error:

[SerializeField] GameObject Weapon;
void SetWeaponActive(bool active)
    {
         Weapon.GetComponent<ParticleSystem>().emission.enabled = active;       
    }

What does putting the component inside a variable actually do that makes it different?

Hi Geth270,

The reason is that emission is not a variable but a property I think. Most parts of Unity are not open-source, so this is just a guess. In your script editor, hover the mouse cursor over emission to see if you get more information.

If emission is a property, it might be that only the get part is implemented. This means that emission is actually a method returning a value. We cannot assign anything to a method. And that’s why the second piece of code does not work.

Did this clear it up for you?


See also:

When I hover over it in the VS code it tells me that emission is not a variable like you said.

Screenshot

To be honest I still don’t understand why we have to assign the emission to a variable first before being able to set its state. We can’t assign methods to variables either so if emission was a method wouldn’t that not make sense? I feel like I’m having a brain fart here.

You can check out this site in csharp reference. Be warned it might bring a little more brain fart :wink:

This paragraph is the most relevant I guess:
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.

This is not easy subject to understand, so Id advice to read entire doc on Microsoft site and try to digest it. But dont worry if you dont get now, it will come with more complex subjects. But its very good question IMO.

2 Likes

Ooo, what a revelation! I didn’t know you can read up on compiler errors like that :heart_eyes:
Also, I sort of get it now even from that snippet, it does a good job at getting a general point across. Definetly will read the rest of the article though.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms