0

I am using a struct List with 2 variables. I am trying to set the value of a variable in a loop but I get the error:

Cannot modify the return value of 'List<>.this[int]' because it is not a variable

Why am I seeing this error?

[Serializable]
public struct SetData
{
     public float Time;
     public float Value;
}

public List<SetData> setData;

void Start ()
{
    for (int i = 0; i < setData.Count; i++)
    {
       setData[i].Time= ((float) DateTime.Now.Hour + ((float) DateTime.Now.Minute * 0.01f));
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
John
  • 1
  • Structs are returned from methods by value, which means that when you access `setData[i]` (which is actually syntactic sugar that calls a method) a COPY of the element at that location is returned. If you were allowed to modify that copy, the modification would be thrown away because the value is not stored anywhere. The error is to stop you accidentally doing that. – Matthew Watson Feb 19 '21 at 10:04
  • @MatthewWatson But the link to duplicate answer shows solution to use an array, is there no way I can modify in my code to get the value to the list? – John Feb 19 '21 at 10:06
  • 1
    There is no way other than: `var item = setData[i]; item.Time = something; setData[i] = item;` – Matthew Watson Feb 19 '21 at 10:07
  • While what @MatthewWatson suggested is correct, you could also change your `SetData` struct to be a class, and then `setData[i].Time = ...` would work. – Teodor Vecerdi Feb 19 '21 at 17:13

0 Answers0