- Home /
Problem with checking if null
I am making a small riddle game and you are given a random riddle. When you solve the riddle, the riddle game object is destroyed. I made an array with all the riddles and the script randomly picks 1 riddle. The problem is that if(currentRiddle == null) doesn't work and it moves to if(currentRiddle != null) which works and it causes an error. Is there any way to fix this?
public void PickRandomRiddle()
{
index = Random.Range(0, Riddles.Length);
currentRiddle = Riddles[index];
if (currentRiddle == null)
{
PickRandomRiddle();
}
else if(currentRiddle != null)
{
currentRiddle.SetActive(true);
print(currentRiddle.name);
}
}
How is "Riddles" defined? what's it's type?
Also
and it causes an error
is completely useless. What error? C# and Unity for the most part actually has human readable errors which are accompanied with a stacktrace which tells you exactly where the error occured.
Note that your approach is really dangerous. You call your method recursively until you find by chance a non-null object. In the case that all objects have been destroyed you will run into a stack overflow exception since you can never exit that method and the method keeps calling itself until you run out of stack memory. Even when you ensure that there's at least one non null element in the array, depending on the element count it could take a lot recursion steps. If the element count is high enough (and you are unlucky enough) you can also run into a stack overflow.
Riddle is a public GameObject array public GameObject[] Riddles
I get a null reference exception error on line 14.
Answer by cs120319992 · May 28, 2019 at 02:01 PM
Because currentRiddle have a reference 'Riddles[index]' and it always will be not null. And error?