# Why is GameObject.FindGameObjectsWithTag returning null?

I'm currently working on refactoring my gravity simulator, but I'm running into a problem. I have two GameObjects, both tagged with the tag "Body", as you can see below:

I'm attempting to cache a list of all GameObjects like so:

private GameObject[] _bodies;

...

public void Start()
{
...
this._bodies = GameObject.FindGameObjectsWithTag("Body");
...
}


When I try to use the value this._bodies though, as seen in the foreach loop below, I get a NullReferenceException.

foreach(GameObject body in this._bodies)
{
...
}


I have verified that the value of this._bodies is null, using this piece of code:

Debug.Log(this._bodies);


I'm honestly stumped as to why GameObject.FindGameObjectsWithTag is returning null when I run it. Is there a way to solve this?

For reference, here's the full code involved:

using UnityEngine;
using System.Linq;
using System.Collections.Generic;

[RequireComponent(typeof(Rigidbody))]
public class GravityComponent : MonoBehaviour
{
public double gravitationalConstant = 6.674 * Mathf.Pow(10, -11);
public Vector3 startingForce;

private GameObject[] _bodies;
private Dictionary<GameObject, double> _massProducts;
private Rigidbody _bodyRigidbody;

/// <summary>
/// Initalize various private values and caches, like the
/// cache of bodies, masses, etc.
/// </summary>
public void Start()
{
this._bodyRigidbody = GetComponent<Rigidbody>();
this._bodies = GameObject.FindGameObjectsWithTag("Body");
this._massProducts = this._bodies.ToDictionary(
body => body,
body =>
this.gravitationalConstant
* this._bodyRigidbody.mass
* body.GetComponent<Rigidbody>().mass
);
}

/// <summary>
/// Calculate the attractions between two separate bodies, and
/// then apply the calculated attraction.
/// </summary>
public void ApplyAttraction()
{
foreach(GameObject body in this._bodies)
{
Vector3 bodyPositionDifference = body.transform.position - this.transform.position;
double attraction = this._massProducts[body] / bodyPositionDifference.sqrMagnitude;
}
}

public void FixedUpdate()
{
Debug.Log(this._bodies);
this.ApplyAttraction();
}
}


*gulp*

Simple typographical errors, the bane of every programmer ever. In the end, all I had to do was swap these two lines, simply because I was attempting to use the Rigidbody of the object before I assigned it a value.

this._bodyRigidbody.AddForce(this.startingForce);
this._bodyRigidbody = GetComponent<Rigidbody>();


After swapping, these two lines became this:

this._bodyRigidbody = GetComponent<Rigidbody>();