我正在为程序做一个任务列表,所以我启动了一个List对象。此列表是另一个类的列表,具有根据类型(整合器)执行的操作(任务)的信息。这是一个主机与客户端的谈话,他们都有类(有点不同,只是我对类型的理解(客户端任务类型0!=主机任务类型0))和我的主机列表完美,但客户端没有。
在尝试添加(NetObject)类时,我的NetObjects List返回ArgumentOutOfRangeException(我将保留代码示例)。我不知道为什么这是一个东西,因为List应该是无限的,当你添加时没有索引或什么(它说索引必须是非负的并且小于集合的大小)。
这是错误:
ArgumentOutOfRangeException:索引超出范围。必须是非负数且小于集合的大小。参数名称:index System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument参数,System.ExceptionResource resource)(at:0)System.ThrowHelper.ThrowArgumentOutOfRangeException()(at:0)System.Collections.Generic.List`1 [T]。 get_Item(System.Int32 index)(at:0)Networking.Update()(在Assets / Scripts / Networking.cs:225)
它说了一些get项,我不知道为什么,因为我在索引中使用(在代码中)任务引用(读取它)并且它只发生在我想要将NetObject添加到Objects类时。我将显示主机代码,因为它有效,客户端没有,我不明白为什么。
我试图将锁定设置为更好(因此没有覆盖),但从我的观点来看,还没有做得更好。
这是客户端中的任务(在Unity中),我使用任务因为Unity不会让游戏内容(位置,生成等)发生变化,如果它不是来自主线程(我使用线程)接收和发送信息(在客户端和主机之间进行交谈))。
for (int i = 0; i < PendingClient.Count; i++) {
if (PendingClient[i].id > -1)
lock (lockingClient) {
switch (PendingClient[i].type) {
case 0:
GameObject go = null;
if (GetObjectFromId(PendingClient[i].id, ref go)) {
go.transform.position = new Vector3(PendingClient[i].px,
PendingClient[i].py, PendingClient[i].pz);
go.transform.rotation = Quaternion.Euler(PendingClient[i].rx,
PendingClient[i].ry, PendingClient[i].rz);
} else {
Objects.Add(new NetObject(PendingClient[i].id,
PendingClient[i].objectType, PendingClient[i].name,
PendingHost[i].prefabName,
Instantiate(Resources.Load("Prefabs/" +
PendingClient[i].prefabName) as GameObject,
new Vector3(PendingClient[i].px, PendingClient[i].py,
PendingClient[i].pz), Quaternion.Euler(PendingClient[i].rx,
PendingClient[i].ry, PendingClient[i].rz))));
}
break;
}
PendingClient.RemoveAt(i);
}
}
错误出现在最后一个的正下方。
以及有效的主机代码:
for (int i = 0; i < PendingHost.Count; i++) {
lock (lockingHost) {
if (PendingHost[i].id > -1) {
switch (PendingHost[i].type) {
case 0: // Add Object
Objects.Add(new NetObject(PendingHost[i].id, PendingHost[i].objectType, PendingHost[i].name, PendingHost[i].prefabName, Instantiate(Resources.Load("Prefabs/" + PendingHost[i].prefabName) as GameObject, Vector3.zero, Quaternion.identity)));
break;
case 1: // Change Transform
GameObject go = null;
GetObjectFromId(PendingHost[i].id, ref go);
go.transform.position = new Vector3(PendingHost[i].px, PendingHost[i].py, PendingHost[i].pz);
go.transform.rotation = Quaternion.Euler(PendingHost[i].rx, PendingHost[i].ry, PendingHost[i].rz);
break;
}
PendingHost.Remove(PendingHost[i]);
}
}
}
我不是一名信息工程师,但我试图制作更好的代码。
谢谢你提前。
你打电话
PendingClient.RemoveAt(i);
内
for (int i = 0; i < PendingClient.Count; i++) {
所以i
最终超出范围。
除此之外:不要做几十次PendingClient[i]
var current = PendingClient[i]
在前面,然后使用current
。