我正在制作多人游戏,我在游戏中添加玩家时遇到了一些问题。我将列表更改为hashset,因为我不想要公开的值。首先制作新的hashset:public static HashSet<Players> PlayersList = new HashSet<Players>();
球员类:
public class Players
{
public int ID;
public string IP;
public string name;
public int locationX;
public int locationY;
public int locationXLatest;
public int locationYLatest;
public int dir;
public bool PlayerConnected = false;
public bool PlayerDisconnected = false;
}
使用for(ERROR)在游戏中添加玩家:
for (int i = 0; i < Globals.Globals.PlayersList.Count; i++)
{
var ent = Globals.Globals.PlayersList[i]; //<-- ERROR! WORKING IF USING LIST BUT GETTING THIS ERROR IF I'M USING HASHSET: Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.HashSet<Players>
if (ent.name != null && !ent.PlayerConnected && !ent.PlayerDisconnected)
{
ent.PlayerConnected = true;
//My secret code :D Addind player in game :3
}
}
使用foreach在游戏中添加玩家(工作,但如果列表修改 - &gt;崩溃)
foreach (var ent in Globals.Globals.PlayersList)
{
if (ent.name != null && !ent.PlayerConnected && !ent.PlayerDisconnected)
{
ent.PlayerConnected = true;
//My secret code :D Addind player in game :3
}
}
如果使用列表,则工作正常,但新列表项始终是垃圾邮件,因为添加了播放器添加循环,检查连接是否打开。或者它可能使用列表但没有得到重复的值?我尝试make check是添加了玩家,但随后玩家没有显示......
答案 0 :(得分:0)
您是否尝试在调用结束时添加.ToArray()以在迭代时缓存列表?
foreach (var ent in Globals.Globals.PlayersList.ToArray())
...
此外,如果您想确保玩家每个ID都是唯一的,您可以将它们添加到ID为键的字典中,或者为Player类实现哈希码。
Dictionary<int, Players> PlayersList;
然后像这样迭代它们:
foreach (var ent in Globals.Globals.PlayersList.Values)
同样,如果要修改循环内的PlayersList,则可能必须使用.ToArray()。
答案 1 :(得分:0)
HashSet
不包含索引器。既然你不关心集合中Player
的位置是什么,你只需使用foreach
代替它,它也会为你节省一些代码行:
foreach (var player in Globals.Globals.PlayersList)
{
if (player.name != null && !player.PlayerConnected && !player.PlayerDisconnected)
{
player.PlayerConnected = true;
//My secret code :D Addind player in game :3
}
}