我创建了一个名为Teams的字典,并使用一个结构来容纳整数,字符串和布尔值。
因此,如果有人加入红队,则布尔值将是错误的,以防止其他玩家加入同一支球队。
我试图将布尔值设置为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 };
}
答案 0 :(得分:3)
您的类型定义为:
public struct myCustomType
{
public string name;
public bool flag;
}
Teams
是Dictionary<int, myCustomType>
。当您尝试类似的操作时:
Teams[1].flag = false;
由于Teams[1]
只是值(Dictionary<,>
索引器获取器的返回值)而失败。
您的类型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'.
有人认为mutable structs evil。
答案 1 :(得分:1)
这似乎是一种反模式。使您的结构不可变(无论如何,您可能都不需要结构,尤其是在团队需要其他功能的情况下):
public struct myCustomType
{
public string Name { get; }
public myCustomType(string name)
{
this.Name = name;
}
}
创建一组可用的团队,这些团队的填充方式类似于addteams
方法:
public Dictionary<string, myCustomType> AvailableTeams; //color, team
public void InitializeTeams()
{
AvailableTeams = new Dictionary<string, myCustomType>()
{
["Yellow"] = new myCustomType("Yellow"),
["Red"] = new myCustomType("Red"),
["Blue"] = new myCustomType("Blue"),
["Green"] = new myCustomType("Green")
};
}
当玩家加入一个团队时,将该团队从可用组中删除,并将其添加到一组ActiveTeam中:
public Dictionary<int, myCustomType> ActiveTeams; //player #, team
public void JoinTeam(int playerNumber, string teamColor)
{
if (!AvailableTeams.TryGetValue(teamColor, out myCustomType team)
// handle team already taken.
ActiveTeams.Add(playerNumber, team);
AvailableTeams.Remove(teamColor);
}