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.