[英]edit Struct value in Unity C#
我創建了一個名為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 };
}
您的類型定義為:
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'.
有人認為可變結構是邪惡的 。
這似乎是一種反模式。 使您的結構不可變(無論如何,您可能都不需要結構,尤其是在團隊需要其他功能的情況下):
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.