Hello. First time help seeker, and I greatly appreciate any help you guys can give.
I want to build a list of game objects based on a certain criteria. To keep this example simple, let’s say that this list will be game objects that are within sight of the player at a specific frame X. Then I want to later test a selected game object to see if it was spotted by the player during frame X.
Here’s a simplified version of the code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerControls : MonoBehaviour {
public List <GameObject> spotted = new List<GameObject>();
public GameObject enemyObject; // starts as null, used to hold a specific
// object for testing, then set to null again
void ScanArea()
{
RaycastHit hit;
if (Physics.Linecast(player.position, target1.position, out hit))
{
if (currentHit.collider.gameObject.tag == "Enemy")
{
spotted.Add(currentHit.collider.gameObject);
}
}
// multiple targets will be linecasted in this way
}
void TestGameObject()
{
enemyObject = // some object that is going to be tested
foreach (GameObject obj in spotted)
{
if (enemyObject == obj)
{
DoSomething();
}
}
}
}
What is happening is that the test works when I test the object that happened to be the first object added to the list “spotted” but if I test any of the other objects that I know are in that list, they do not work.
I have used a workaround where I alter the color of spotted objects then test for color when I do my test, but that seems unnecessary and unideal. I’m sure I’m missing something obvious but I can’t seem to figure out what :X
EDIT: looks like this is the error that might be causing me troubles: “InvalidOperationException: Collection was modified; enumeration operation may not execute.” I’m not really sure why I’m getting this error though.