I’m trying to make a custom gravity system, and right now I’m testing the foreach() and AddForce system, but for some reason AddForce isn’t working.
public class mass : MonoBehaviour {
private Rigidbody[] rigidbodies;
// Use this for initialization
void Start () {
rigidbodies = FindObjectsOfType<Rigidbody>;
}
// Update is called once per frame
void Update () {
foreach(GameObject other in rigidbodies)
{
other.AddForce(Vector3.down);
}
}
}
the AddForce command is highlighted red and isn’t letting me run the simulation, the error message says “error CS0428: Cannot convert method group ‘FindObjectsOfType’ to non-delegate type ‘UnityEngine.RigidBody[ ]’. Consider using parenthesis to invoke the method”
Can someone please explain what I’m doing wrong here?
Alright, I figured it out right after I posted the thread, here’s the new code:
public class mass : MonoBehaviour {
private Rigidbody[] rigidbodies;
// Use this for initialization
void Start () {
rigidbodies = FindObjectsOfType<Rigidbody>();
}
// Update is called once per frame
void Update () {
foreach(Rigidbody other in rigidbodies)
{
other.AddForce(Vector3.up);
}
}
}
Turns out I forgot to put in the parentheses
Note: For forces you’re applying constantly, you should be doing that within FixedUpdate(), not in Update(). Update is frame-rate dependent, which means the physics would behave differently on different people’s systems depending on how fast their machines were.
An exception to this is applying a one-time force, like a force when a character jumps in the air. But in your case, put that logic in FixedUpdate.
That wasn’t the error. AddForce is a function that belongs to Rigidbodies. In the first script you posted, “other” in the foreach loop was a GameObject, whereas you changed it to a Rigidbody in the second script you posted.