- Home /
C# if Statement Checking for Null Causing Null?
I have this script in which I'm checking to see if a gameobject variable is null. However when I run the script the console is telling me that the if statement is causing a null reference exception. Any ideas why? Both shooterPlayer and glaveRotateAround are assigned so the null reference exception isn't coming from them.
using UnityEngine;
using System.Collections;
public class AssignShipPlayer : MonoBehaviour {
public GlaveRotateAround glaveRotateAround;
public ShooterPlayer shooterPlayer;
// Use this for initialization
void Awake () {
shooterPlayer = GetComponent<ShooterPlayer>();
}
// Update is called once per frame
void Update () {
if(shooterPlayer.curShotGO != null){
glaveRotateAround = shooterPlayer.curShotGO.GetComponent<GlaveRotateAround>();
glaveRotateAround.ship = transform.parent.transform;
}
}
}
Answer by jdean300 · Aug 25, 2016 at 10:21 PM
There are two ways for this to be happening.
1) shooterPlayer is null, which would mean your GetComponent call in Awake is failing. Try printing out the value of shooterPlayer before the if statement: Debug.Log(shooterPlayer)
. You say it is assigned, which seems like you're talking about from within the inspector - but your Awake call is going to overwrite that value.
2) If curChotGo is a property and it's getter throws the exception
Okay so since I already assigned shooterPlayer from within the inspector I removed the awake function and added Debug.Log(shooterPlayer) before the if statement. I ran the script again and judging from the console shooterPlayer seems to fluctuate from being null to being the actual gameobject like it's supposed to though I'm not sure why. I don't have any scripts that unassign shooterPlayer.
using UnityEngine;
using System.Collections;
public class AssignShipPlayer : $$anonymous$$onoBehaviour {
public GlaveRotateAround glaveRotateAround;
public ShooterPlayer shooterPlayer;
// Update is called once per frame
void Update () {
Debug.Log(shooterPlayer);
if(shooterPlayer.curShotGO != null){
glaveRotateAround = shooterPlayer.curShotGO.GetComponent<GlaveRotateAround>();
glaveRotateAround.ship = transform.parent.transform;
}
}
}
Your answer
Follow this Question
Related Questions
C# Creating a List of If Statements 3 Answers
Need help with multiple if statements. 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to put null & non-null value calculation in 1 if statement 2 Answers