Can't modify Struct variables C#

Hello,

I have a struct called WeaponType, and in it I have approximately 10 variables.

Upon calling “WeaponType.CurrentWeapon.Ammo = ,” I received an error that I couldn’t modify the value because it wasn’t a variable.

Okay, well that’s fine. So I added a function called SetAmmo(int amount) where I thought I would modify the value directly on the struct.

With that function I’m able to “change” the value from the same to the same.(no actual change is noted) Later found out this is because of the fact that it’s like a skinwalker from Supernatural and created another instance of itself. (okay, bad reference)

After doing research on it, I don’t know how to change it from “mutable” to “immutable,” mainly because I don’t know what that means.

Can anyone shed some light on this please?

Please provide the code showing the deceleration of WeaponType. Also, where are you accessing WeaponType.CurrentWeapon.Ammo? I'm guessing from another script. Id so, please show the code referencing the script.

Are both scripts on the same object? You know you need to write it like so GetComponent(); right?

I'm guessing you are drag'droping the object with the Weapons script. When you are trying to call the weapon type, it should be: waepons.weaponType.Ammo and so on.

1 Answer

1

You cannot modify the values inside a struct returned from another component the way you are - and for good reason. A struct is passed by value.

When you do this:

    WeaponType currentWeapon get{return _currentweapon;} set {_curentWeapon = value;}

You return a copy of _currentWeapon.

So if you were to do someObject.currentWeapon.maxWeaponAmmo = 5 - you would be doing that on the copy that only existed while that line executed and was immediately thrown away afterwards. So the compiler realises that this isn’t smart and refuses it.

Either

  1. Make it a class which won’t have that problem

  2. Take the value into a local variable, change the property and set it back. That way you update the copy and assign the copy back.

    var weapon = something.currentWeapon;
    weapon.maxWeaponAmmo = 5;
    something.currentWeapon = weapon;

Note that structs can be a lot slower than classes because of all of the hidden copying.

Thanks for the overview of issues with Structs... that information was kind of left out when I read a few months ago that "Structs are just smaller classes that can hold values and functions!" Tried to avoid using a new class for this, but it seems like that won't be happening lol. Thanks again, truly enlightened me.

Yeah it's those techy details - especially for ex C++ programmers where they are almost identical to classes. Utility things (think Vector3/Quaternion etc) that you create and use everywhere for a few instants and then forget about should always be structs in Unity. If it lives for a significant time it should probably be a class. It's all the intermediate things which are a problem!