我一直在基于碰撞与滑动算法开发一个碰撞响应系统。
但是,我在运行过程中遇到了一个错误。以下是包含错误的代码:
// 省略部分导入语句
[System.Serializable]
public class CollisionRepsonse
{
public float RemainingVelocity;
public RaycastHit CollisonHit;
public Vector3 CollisionHitLocation;
public Vector3 OutputForce;
}
public class NewBehaviourScript : MonoBehaviour
{
public Vector3 CurrentInputDir;
public float BaseVelocity = 5f;
[SerializeField] List<CollisionRepsonse> CollisionHits;
RaycastHit InitialCollisonHit;
bool FirstCollisionHit;
public int i = 0;
void Update()
{
if(Physics.CapsuleCast(transform.position, transform.position, 0.5f, CurrentInputDir, out InitialCollisonHit, BaseVelocity))
{
// 检查并记录首次碰撞
if (CollisionHits.Count == 0f)
{
FirstCollisionHit = true;
}
if (FirstCollisionHit)
{
CollisionHits.Add(new CollisionRepsonse{});
FirstCollisionHit = false;
}
if (CollisionHits.Count != 0f)
{
CollisionResponseFunction();
}
void CollisionResponseFunction()
{
// 遍历碰撞列表
foreach(CollisionRepsonse CollisionRepsonse in CollisionHits)
{
if (i == 0)
{
// 计算并存储初始碰撞数据
CollisionHits[i].CollisionHitLocation = InitialCollisonHit.point;
CollisionHits[i].RemainingVelocity = BaseVelocity - Vector3.Distance(transform.position, CollisionHits[i].CollisionHitLocation);
CollisionHits[i].OutputForce = Vector3.ProjectOnPlane(CurrentInputDir, InitialCollisonHit.normal);
}
else
{
// 处理后续碰撞数据(注释掉的部分)
}
if (CollisionHits[i].RemainingVelocity > 0f)
{
CollisionHits.Add(new CollisionRepsonse{});
i++;
}
}
}
}
}
}
遇到的错误是:
InvalidOperationException: Collection was modified; enumeration operation may not execute.
当我在foreach
循环中添加以下计算和赋值代码时,会引发此错误:
if (i == 0)
{
CollisionHits[i].CollisionHitLocation = InitialCollisonHit.point;
CollisionHits[i].RemainingVelocity = BaseVelocity - Vector3.Distance(transform.position, CollisionHits[i].CollisionHitLocation);
CollisionHits[i].OutputForce = Vector3.ProjectOnPlane(CurrentInputDir, InitialCollisonHit.normal);
}
然而,当我移除这部分代码后,程序就能正常运行。