ArgumentOutOfRangeException:参数超出范围。 参数名称:index System.Collections.Generic.List`1 [UnityEngine.Vector3] .get_Item(Int32 index)(at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633 ) SphereBuilder.MoveShips()(在Assets / MyScripts / SphereBuilder.cs:75) SphereBuilder.Update()(在Assets / MyScripts / SphereBuilder.cs:65)
在剧本的顶部
private float distanceTravelled;
public bool updateOn = true;
private List<Vector3> lastPositions = new List<Vector3>();
private List<float> allDistances = new List<float>();
int countpos = 0;
启动功能
private void Start()
{
UpdateSpheres ();
spheres = GameObject.FindGameObjectsWithTag("MySphere");
foreach (Transform child in spheres[0].transform)
{
lastPosition = new Vector3(child.transform.position.x,child.transform.position.y,child.transform.position.z);
lastPositions.Add (lastPosition);
}
}
在更新功能中:
void Update()
{
if (updateOn == true) {
//whatever you want update to do.
foreach (Transform child in spheres[0].transform) {
child.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
Vector3 lp = lastPositions [countpos];
distanceTravelled += Vector3.Distance (child.transform.position, lp);
allDistances = new List<float> ();
allDistances.Add (distanceTravelled);
countpos ++;
}
}
if (countpos == spheres.Length)
{
updateOn = false;
distanceTravelled = 0;
countpos = 0;
}
// if you want certain parts of update to work at all times write them here.
foreach (Transform child in spheres[0].transform)
{
child.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
}
}
我要做的是存储孩子的起始位置,并存储孩子的行走距离。
然后以某种方式在另一个函数中,我可能想每次循环查看孩子,并检查每个孩子是否达到了特定的距离:
if (allDistances[0] >= 300000)
{
}
但是,然后allDistances [0]然后循环使用计数器,例如:
if (allDistances[counter] >= 300000)
{
}
第一个问题是超出范围的例外,不确定我为什么会得到它。 球体包含20个孩子。
第二个问题是每个孩子在每个框架检查每个孩子的行走距离以及当任何一个孩子到达300000时与他做某事的地方和方法。
答案 0 :(得分:1)
我建议使用if
子句来检查countpos
是否不超过列表的长度:
foreach (Transform child in spheres[0].transform) {
child.transform.position += Vector3.forward * Time.deltaTime * moveSpeed;
if (countpos < lastPositions.Count() && countpos >= 0) {
Vector3 lp = lastPositions [countpos];
distanceTravelled += Vector3.Distance (child.transform.position, lp);
allDistances = new List<float> ();
allDistances.Add (distanceTravelled);
countpos ++;
}
}