Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Struct variable doesn't change

Discussion in 'Scripting' started by unity_1236alman, Dec 19, 2020.

  1. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    Hi, where's the error?
    Code (CSharp):
    1.  
    2. {
    3.      struct rollTreshold
    4.     {
    5.         public string defenceName;
    6.         public float treshold;
    7.  
    8.         public rollTreshold(string defenceName, float treshold) : this()
    9.         {
    10.             this.defenceName = defenceName;
    11.             this.treshold = treshold;
    12.         }
    13.  
    14.         public void SetTreshold(float amount)
    15.         {
    16.             treshold = amount;
    17.         }
    18.     }
    19.  
    20.      rollTreshold[] rollTresholds = new rollTreshold[1];
    21.  
    22.      void Modify()
    23.      {
    24.              rollTresholds[0].SetTreshold(rollTresholds[0].treshold + 0.5) //output is rolltresholds[0] not modified
    25.      }
    26. }
    27.  
     
  2. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    Code (CSharp):
    1. rollTresholds[0].treshold += 0.5f;
     
  3. VolodymyrBS

    VolodymyrBS

    Joined:
    May 15, 2019
    Posts:
    150
    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.
     
  4. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    yes, i am using an array. So how can i avoid that?
     
  5. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    This doesn't work because "rollTresholds[0].treshold is not a variable"
     
  6. raarc

    raarc

    Joined:
    Jun 15, 2020
    Posts:
    535
    what is it then

    why do you think this will work then?
    Code (CSharp):
    1. treshold = amount;
     
  7. willemsenzo

    willemsenzo

    Joined:
    Nov 15, 2012
    Posts:
    585
    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.
     
  8. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    Thanks
     
    willemsenzo likes this.