Monday, May 20, 2024
HomeGame Developmentc# - Unity: Adding object-level gravitational force to all objects by object...

c# – Unity: Adding object-level gravitational force to all objects by object mass


So, for conversational clarity/brevity, I have 3 sphere gameobjects, each with their own Rigidbody component. They all have a tag of ‘body’. The 3 spheres have progressively larger masses.

  1. body1 mass: 100000
  2. body2 mass: 10000
  3. body3 mass: 1000

So, what I am seeking to do is to assign a gravitational force to each object by using the Newtonian formula for gravitational force.

Gravitational Force Formula

Perhaps that’s a bit too much for the moment. The main issue I am seeking to address is that I have this code which seeks to assign a gravitational force to each body;

void Start() {
  selfBodyName = this.name;
  selfMass = GameObject.Find(selfBodyName).GetComponent<Rigidbody>().mass;
  bodies = GameObject.FindGameObjectsWithTag("body");

  // Trying to fill array of each body's rigidbody reference.
  for(int i = 0; i < bodies.Length; i++) {
    bodiesRb[i] = bodies[i].GetComponent<Rigidbody>();
  }
}

Problem I am encountering is that when the for loop runs, it gives me the infamous “NullReferenceException: Object reference not set to the instance of an object.”

So, I just would like an extra set of eyes to tell me if I have overlooked something. Known facts:

  • I know that the bodies array is populated and its length = 3.
  • Each sphere gameobject has a rigidbody component with the respective masses set.

So, what am I overlooking here?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments