GetComponent hates me

I’m trying to call the function spawnWreckage() from a script called Ground.cs inside a unique object in my Scene, called Ground, with the following line of code:

transform.Find("Ground").GetComponent<Ground>().spawnWreckage((int)(distTraveled / 5));

But I get the dreaded

NullReferenceException: Object reference not set to an instance of an object

for some reason.

I have verified that I have a Ground object and that it has the desired Ground script. What gives?

NOTE: When I split that line up into more manageable sections, it always crashes at the GetComponent() stage, which is why I titled this post as it is.

try with

GameObject.Find("Ground").GetComponent<Ground>().spawnWreckage((int)(distTraveled / 5));

Where do you have this piece of code? transform.Find searches for a child object of the given name. If your ground object is not a child of the object from which this code is executed then no wonder this gives a NullReferenceException.

If you wanted to find the object of type Ground in the entire scene, then write this code instead:

Ground myGround = FindObjectOfType(typeof(Ground)) as Ground;
myGround.spawnWreckage((int)(distTraveled / 5));