Hi, I’m getting this error (InvalidOperationException: Collection was modified; enumeration operation may not execute.) It’s in my OnTriggerStay, it doesn’t break the game and the script continues fine. I was wondering is there a way I can have this error not pop -up.
I guess because I’m removing the target from the list in the OnTriggerStay, but I do this because I destroy the target seconds later after death and if it’s still in the list I get a missing component. I remove it this way just in case the player does not move out of range for the OnTriggerEixt to remove the target from the list. It works but I still get this error.
This is a video of it in action.
here is the code
[SerializeField] List<GameObject> characterTargets;
[SerializeField] GameObject mainTarget;
private void Update()
{
if (characterTargets.Count == 0)
{
mainTarget = null;
}
}
public void OnSkillEnter(Collider other)
{
if (isEnemyAI == false)
{
if (other.tag == "Enemy")
{
characterTargets.Add(other.gameObject);
}
}
else
{
if (other.tag == "Player")
{
characterTargets.Add(other.gameObject);
}
}
}
public void OnSkillStay(Collider other)
{
float distanceToClosestTarget = Mathf.Infinity;
foreach (GameObject target in characterTargets)
{
float distancetoTarget = (target.transform.position - this.transform.position).sqrMagnitude;
Health health = target.GetComponent<Health>();
if (characterTargets.Count != 0)
{
if (distancetoTarget < distanceToClosestTarget)
{
distanceToClosestTarget = distancetoTarget;
mainTarget = target;
}
}
if (health.IsDead())
{
characterTargets.Remove(other.gameObject);
}
// Fire Skill burn over time
if (burnSPInUse == true)
{
target.GetComponent<Spirit>().ReduceSpirit(fireSkillBurnAmount);
}
}
return;
}
public void OnSkillExit(Collider other)
{
if (isEnemyAI == false)
{
if (other.tag == "Enemy")
{
characterTargets.Remove(other.gameObject);
}
}
else
{
if (other.tag == "Player")
{
characterTargets.Remove(other.gameObject);
}
}
}