- Home /
Why am I getting a null reference error?
PlayerHitNetworkScript phns = yourPlayer.GetComponent();
Also I use to get an error from this but my game would still run, but now I'm getting the same error and the game pauses.
If this is the line, then 'yourPlayer' is null. We would need to see the rest of the script to give you any more information on why it is null.
or search for one of the million questions about null references.
GameObject yourPlayer = GameObject.FindGameObjectWithTag("myPlayer");
PlayerHitNetworkScript phns = yourPlayer.GetComponent<PlayerHitNetworkScript>();
Still getting the null reference error, for some reason unity goes ahead even though it's an error and runs the game normally but other times it doesn't run and pauses. I don't know why it changes but right now it's pausing and isn't going ahead. Not sure why it's saying yourPlayer is null since I'm creating it in the line above.
I'm trying to put it in a try catch block but not really sure how to do it
try{
yourPlayer = GameObject.FindGameObjectWithTag("myPlayer");
phns = yourPlayer.GetComponent<PlayerHitNetworkScript>();
}
catch(){
}
What would I need in the catch parameters? I tried putting "Exception e" but that didn't work.
You said "since I'm creating it in the line above". I can see in the line above you are asking Unity to find a game object, but it's possible Unity can't/doesn't find myPlayer. It's worth checking that you get a value assigned to yourPlayer
before you try and access a component it may or may not contain. What happened when you did catch(Exception e)
?
Answer by spraycanmansam · Mar 15, 2014 at 08:42 PM
From the information you've provided, it's safe to assume that your 'yourPlayer' variable is null. It's always a good idea to assume GetComponent returns null and deal with it then, something like ---
yourPlayer = GameObject.FindGameObjectWithTag("myPlayer");
if(yourPlayer != null) {
// ...
}
else {
Debug.LogError("Could not find 'myPlayer'");
}
Double check your player and tags.
I get the Could not find "myPlayer" error in debug but unity still pauses in the editor. When I run the exe it works fine though.
Your answer
