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?
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
-
Make it a class which won’t have that problem
-
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.