How to update AmmoData attribute

Zaddo

Active member
Hi,
Quick question I hope. I couldn't track down how to update the AmmoData attribute override value. Is the example below the correct method?

It is unusual because AmmoData is a Struct and the properties are readonly.

EDIT:
I did find this sample code (bottom of page, ItemAmounts), https://opsive.com/support/documentation/ultimate-inventory-system/attributes/
In this example the ItemSlots can be modified if the override value equals the GetValue(). But with the AmmoData, you cannot override, you always have to create a new instance? Is this correct?
Also, from my understanding of garbage collection and structs, the new struct will not add to garbage, because it is created on the Heap and when you update the override value, the values will map into the already allocated memory for the struct in the class?


Thx.

C#:
int ammo = 5;
var ammoDataAttribute = item.GetAttribute<Attribute<AmmoData>>("AmmoData");
if (ammoDataAttribute == null) return;

AmmoData ammoData = ammoDataAttribute.GetValue();
if (ammoData.ClipRemaining != ammo)
{
    ammoData = new AmmoData(ammoData.ItemDefinition, ammoData.ClipSize, ammo);
    ammoDataAttribute.SetOverrideValue(ammoData);
}
 
Last edited:
Your code seems good to me.

As you mentioned AmmoData is a struct, which means it is simply data, not an object. It's recommended to use structs in the attribute system to avoid issues with the same object being used in multiple items.

For example, imagine you have a sword with a list of upgrades. The original list is in Default Item attribute, all other sword inherit this attribute value. So now if you change the list of upgrades by getting the attribute value and changing the contents of the list, all the swords will have their upgrades change. That's why you should make a new list, copy the contents of the original one and then modify it before using the SetOverrideValue function.

structs that are immutable* forces you to create a new value.

*Immutable means that they cannot change value after it has been initialized. Its good pratice to make structs immutable, it takes a few more lines of code but it can prevent some user error bugs. There is a lot to read about immutable struct online if you are interested.
 
Top