- Home /
Problem is not reproducible or outdated
How to use GetComponent in a foreach loop?
I have a list of targets as Transforms and I basically just want to iterate through and do damage to each one. Health is in a script on each game object.
I have the code set up as such:
foreach(Transform target in attackList){
Target targetScript = target.gameObject.GetComponent<Target>();
targetScript.health -= 100;
}
However, I'm getting the error: "foreach statement cannot operate on variables of type UnityEngine.GameObject' because it does not contain a definition for
GetEnumerator' or is not accessible".
I gather I can't use the target.gameObject.GetComponent because gameObject isn't "Enumerator"able(word?). Having trouble figuring out how to get the component without accessing the game object though.
Answer by poncho · Jan 31, 2014 at 07:29 PM
if its a list use a for, if its an array you can use the foreach, try
for(int i =0;i< attackList.Count; i++)
{
attackList[i].GetComponent<Target>().healt -= 100;
}
Answer by Bunny83 · Nov 05, 2019 at 05:19 PM
Since the question got already bumped I'll post an actual answer even the OP hasn't been online during the last 5 years...
The error clearly states:
The foreach statement cannot operate on variables of type UnityEngine.GameObject
this clearly shows that "attackList" is not an array or generic List<Transform>
as the OP said but that it is just a GameObject variable. Of course the GameObject class doesn't have a GetEnumerator method which is required by the foreach pattern matching that the compiler performs. Actually looking at the provided line numbers of the errors would have helped. The error clearly is not related to the GetComponent line
Answer by Petrit24 · Nov 05, 2019 at 02:52 PM
You could use a foreach loop like so:
foreach (GameObject obj in aList)
{
Type variableName = obj.GetComponent<Type>();
}