Modify Struct variable in a Dictionary

前端 未结 4 725
孤独总比滥情好
孤独总比滥情好 2020-11-27 19:51

I have a struct like this:

public struct MapTile
{
    public int bgAnimation;
    public int bgFrame;
}

But when I loop over it with forea

4条回答
  •  失恋的感觉
    2020-11-27 20:41

    tilesData[tile.Key] is not a storage location (i.e., it's not a variable). It's a copy of the instance of MapTile associated with the key tile.Key in the dictionary tilesData. This is what happens with struct. Copies of their instances get passed around and returned everywhere (and is a large part of why mutable struct are considered evil).

    What you need to do is:

        MapTile tile = tilesData[tile.Key];
        if (tile.bgFrame >= tile.bgAnimation)
        {
            tile.bgFrame = 0;
        }
        else
        {
            tile.bgFrame++;
        }
        tilesData[tile.Key] = tile;
    

提交回复
热议问题