首页 > 解决方案 > 在 Unity C# 中编辑结构值

问题描述

我创建了一个名为 Teams 的字典,并使用一个结构来保存一个整数、一个字符串和一个布尔值。

因此,如果有人加入红队,则 bool 将为 false,以防止其他玩家加入同一队。

我试图将布尔值设置为 false,但它失败了。

public Dictionary <int , myCustomType> Teams = new Dictionary<int,myCustomType>();

private ExitGames.Client.Photon.Hashtable m_PlayerCustomPropeties = new ExitGames.Client.Photon.Hashtable();

private void addTeams() 
{
    myCustomType t=new myCustomType();

    t.name="Yellow"; 
    t.flag= true;
    Teams.Add(1,t);

    t.name="Red"; 
    t.flag= true;
    Teams.Add(2,t);

    t.name="Blue"; 
    t.flag= true;
    Teams.Add(3,t);

    t.name="Green"; 
    t.flag= true;
    Teams.Add(4,t);

    Debug.Log("Teams created.");
}

public void getPlayers() 
{
    Debug.Log(Teams[1].flag);
    Teams[1] = new myCustomType { flag = false };
}

标签: c#unity3d

解决方案


您的类型定义为:

public struct myCustomType
{
  public string name;
  public bool flag;
}

并且Teams是一个Dictionary<int, myCustomType>. 当您尝试以下操作时:

Teams[1].flag = false;

它失败了,因为Teams[1]它只是一个Dictionary<,>索引器 getter 的返回值)。

您的类型myCustomType是可变结构。该结构是按值返回的,因此尝试修改返回的值的副本是没有意义的。

你会需要:

var mct = Teams[1];  // 'mct' is a copy of the value from the 'Dictionary<,>'.
mct.flag = false;    // You modify the copy which is allowed because 'mct' is a variable.
Teams[1] = mct;      // You overwrite the old value with 'mct'.

有些人认为可变结构是邪恶的。


推荐阅读