- Home /
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.
On a side note, does anyone have any tips for na$$anonymous$$g here. Ground representing both a named game object and a script component is far from ideal, but what's the best approach?
Answer by fafase · Mar 30, 2012 at 06:54 AM
try with
GameObject.Find("Ground").GetComponent<Ground>().spawnWreckage((int)(distTraveled / 5));
Answer by Kryptos · Mar 30, 2012 at 07:57 AM
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));
Your answer

Follow this Question
Related Questions
Getting NullReference when calling Instantiate from another script 0 Answers
Get Component or Check if Null SoftLocks Game (C#) 1 Answer
How do I determine the presence of a script on an object? 1 Answer
Why is this null? Finding a script on an object 3 Answers
get component null reference 2 Answers