foreach Gameobject in array problems

I am making a script for magnetism. I have an electromagnet and two metal cubes. I want all of the cubes to attract to the electromagnet. Here is my script:

using UnityEngine;
using System.Collections;

public class eMag : MonoBehaviour {

	private float xMagnitude;
	private float yMagnitude;
	private float zMagnitude;
	[Range(-50,50)]
	public float magneticForce = 1;

	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		GameObject[] magnets = GameObject.FindGameObjectsWithTag("Magnetic");
		foreach(GameObject magnet in magnets)
		{
			xMagnitude = (GameObject.FindWithTag("Electromagnet").transform.position.x - GameObject.FindWithTag("Magnetic").transform.position.x) * magneticForce;
			yMagnitude = (GameObject.FindWithTag("Electromagnet").transform.position.y - GameObject.FindWithTag("Magnetic").transform.position.y) * magneticForce;
			zMagnitude = (GameObject.FindWithTag("Electromagnet").transform.position.z - GameObject.FindWithTag("Magnetic").transform.position.z) * magneticForce;
			GameObject.FindWithTag("Magnetic").GetComponent<Rigidbody>().AddForce(xMagnitude,yMagnitude,zMagnitude);
		}
	}
}

The electromagnet is tagged as “Electromagnet” and the metal cubes are tagged as “Magnetic”.

This works flawlessly, however it only works for one cube. I can’t figure out why the foreach loop is not looping for all cubes labeled “Magnetic”. My apologies for being relatively new to C# and not knowing how to use the foreach loop function.

Thank you for your consideration.

Your loop iterates ovver each GameObject with Tag “Magnetic”. The problem lies within the loop.

In the loop you use three times (GameObject.FindWithTag(“Electromagnet”). I think you have only one such elektromagnet in your game? If this is true, cache this object first:

private Transform m_ElectroMagnet;

void Start () {
    m_ElectroMagnet = GameObject.FindWithTag("Electromagnet").Transform;
}

The second problem is, that GameObject.FindWithTag(“Magnetic”) always finds the same object with this Tag in the Hierarchy. You have already searched all objects with this tag, before the loop starts. So do something like this:

void Update () {
GameObject[] magnets = GameObject.FindGameObjectsWithTag("Magnetic");
foreach(GameObject magnet in magnets)
{
xMagnitude = m_ElectroMagnet.position.x - magnet.transform.position.x) * magneticForce;
yMagnitude = m_ElectroMagnet.position.y - magnet.transform.position.y) * magneticForce;
zMagnitude = m_ElectroMagnet.position.z - magnet.transform.position.z) * magneticForce;
magnet.GetComponent<Rigidbody>().AddForce(xMagnitude,yMagnitude,zMagnitude);
}
}