but it gives error.I dont understand what do you mean by you assume it if script can’t take the variable because it is null it gives nullreference exception;
herosave.locationnn is an array. An array itself can be null.
// By default not initialized, thus null.
int[] numbers;
// Trying to access array index 0.
// Will cause a null reference exception because numbers is not initialized.
if(numbers[0] > 1)
{
// Do Something
}
// Null check on the array itself.
// If it isn't also check if the number is higher than 1
if(numbers != null && numbers[0] > 1)
{
}
Thank you it works when ı check if array null but it does not work when ı check if an arrays value null
do you know why
if(herosave.locationnn!=null)
{
x = herosave.locationnn[0];
y = herosave.locationnn[1];
transform.position = new Vector2(x, y);
}
this works
if(herosave.locationnn[0]!=null&& herosave.locationnn[1]!=null)
{
x = herosave.locationnn[0];
y = herosave.locationnn[1];
transform.position = new Vector2(x, y);
}
An array is a reference type. It needs to be initialized before you can request the items from it.
Imagine sitting at a table and having a line of people.
You have to check whether the people are on the list. But you’re just there sitting at the table. There’s no list.
Now you’re being instructed to check the first person. How’re you going to do that without the list?
You’ve never been given the list of people to use to check with.
herosave.locationnn[0], you’re requesting the item at index 0 whilst the array is non existent. Null.
Why it is null? well that’s up to you really. You never initialized it in the first place.
You also might want to tag me next time. I’m not always watching all threads I answer to.
It is fascinating to me to see how long someone will resist doing the simple three-step process that works 100% of the time to fix a null reference error. I think one guy resisted it for a full week before finally doing the first step and then his nullref was fixed in like 60 seconds.
@Kurt-Dekker fixing a null reference is one thing, understanding it is another.
And with understanding, I mean C# basics reference and value types.
Some just don’t grasp the idea that something can be null. If it were a value type it wouldn’t be null.
Then you also have people be like. But this is an array of int and an int is a value type. But the array still is a reference type.
Totally with you but you still must find what variable is null. That part is not optional. The longer that someone goes throwing up “this works but this does not” smoke screens, the longer they delay identifying what that null variable is.
I want to see OP get back to making progress in their game, not spending a day-plus on a nullref.
Why? Because it won’t be very long before the NEXT nullref comes along.