Struct variable doesn't change

Hi, where’s the error?

{
     struct rollTreshold
    {
        public string defenceName;
        public float treshold;

        public rollTreshold(string defenceName, float treshold) : this()
        {
            this.defenceName = defenceName;
            this.treshold = treshold;
        }

        public void SetTreshold(float amount)
        {
            treshold = amount;
        }
    }

     rollTreshold[] rollTresholds = new rollTreshold[1];

     void Modify()
     {
             rollTresholds[0].SetTreshold(rollTresholds[0].treshold + 0.5) //output is rolltresholds[0] not modified
     }
}
rollTresholds[0].treshold += 0.5f;

do you use array in actual code too?
notice that array works a litle bit different that most of other collection types.
Arrays return elements by reference. Most other collections return elements by value.

yes, i am using an array. So how can i avoid that?

This doesn’t work because “rollTresholds[0].treshold is not a variable”

what is it then

why do you think this will work then?

treshold = amount;

Structs are value types and not reference types. To change them you need to make a copy and make the change on the copy, then overwrite the entire original with the copy. Alternatively just change the struct into a class.

Thanks

1 Like