- Home /
Why does empty if statement fix null reference
Hello, today I was trying to centralize my code and I have run into an interesting problem with even more fascinating solution. So the script which is a grandchild of the script that it is finding returns error:
NullReferenceException: Object reference not set to an instance of an object
is while trying to debug it I wrote an if statement that checks if the object is not null at the start and the problem was fixed . Here is how the code looks like after deleting the Debug.Log()
private PlayerControler pControlerSelect;
void Start () {
pControlerSelect = FindObjectOfType<PlayerControler>();
if (pControlerSelect != null)
{
}
WeaponSelect();
}
also the error fires from the line that is in method WeaponSelect() and changing the statement to check if the object is null returns the error
That is weird! Can you post the actual line in WeaponSelect() that throws the error?
private void WeaponSelect()
{
int index = 0;
foreach (Transform weapon in transform)
{
if (index == selectedWeapon)
{
weapon.gameObject.SetActive(true);
}
else
{
weapon.gameObject.SetActive(false);
}
index++;
}
//the fallowing line
pControlerSelect.UpdateCurrentWeapon();
}
Huh. I got nothing... that is super strange though. Hope you're able to figure it out
Does your working if-statement have curly braces?
What I mean, does your code look like:
// Option 1:
if (pControlerSelect != null)
{
}
pControlerSelect.UpdateCurrentWeapon();
// Option 2:
if (pControlerSelect != null)
pControlerSelect.UpdateCurrentWeapon();
The thing is, if it looks like Option 2, then that's not an empty if-statement. If Option 2 is your situation, then the if-statement is stopping "pControlerSelect.UpdateCurrentWeapon();" from being executed when pControlerSelect is null.
Answer by Bunny83 · Sep 07, 2018 at 06:41 PM
No this can't solve or influence anything. I suspect that you have a wrong if statement when you actually have a null reference exception. You most likely did
if (pControlerSelect = null)
instead of
if (pControlerSelect == null)
The first statement will actually set "pControlerSelect" to null while the second will check if it's null.
@Bunny83 The proper syntax for an if statement is
if (theVaribleYouWant == thevalueyouwant)
{
then do this
}
Your answer
Follow this Question
Related Questions
Error "OnTriggerEnter: this message has to be of type: Collider" 0 Answers
erros and bugs 1 Answer
Exporting to iOS device breaks game and causes errors 0 Answers
Strange bug after update to 5.6.0f1 (This is not supported) 2 Answers
Some functions do not work when I build the game.,Some functions don't work when I build the game 0 Answers