I have a struct like this:
public struct MapTile
{
public int bgAnimation;
public int bgFrame;
}
But when I loop over it with foreach to change animation frame I can’t do it…
Here’s the code:
foreach (KeyValuePair<string, MapTile> tile in tilesData)
{
if (tilesData[tile.Key].bgFrame >= tilesData[tile.Key].bgAnimation)
{
tilesData[tile.Key].bgFrame = 0;
}
else
{
tilesData[tile.Key].bgFrame++;
}
}
It gives me compile arror:
Error 1 Cannot modify the return value of 'System.Collections.Generic.Dictionary<string,Warudo.MapTile>.this[string]' because it is not a variable
Error 2 Cannot modify the return value of 'System.Collections.Generic.Dictionary<string,Warudo.MapTile>.this[string]' because it is not a variable
Why can’t I change a value inside a struct which is inside a dictionary?
The indexer will return a copy of the value. Making a change to that copy won’t do anything to the value within the dictionary… the compiler is stopping you from writing buggy code. If you want to do modify the value in the dictionary, you’ll need to use something like:
Note that this is also avoiding doing multiple lookups for no good reason, which your original code was doing.
Personally I’d strongly advise against having a mutable struct to start with, mind you…
Of course, another alternative is to make it a reference type, at which point you could use: