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.

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*.GetComponent<Target>().healt -= 100;*

}

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

You could use a foreach loop like so:

foreach (GameObject obj in aList)
        {

            Type variableName = obj.GetComponent<Type>();

        }