Nulls....... how do I handle it when I ask for something, but it's not there at the moment?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mattkw80

I’ve come across this multiple times, for various objects.

Sometimes I ask for an object, that’s just not going to be there, at that time.
So, my next statement is an IF… as in IF the thing is not there, don’t do anything.

In this example… I am setting a var called mytileint. This works normally… what it does it wherver my player is, it returns the ID of the tile. But, if my player wanders off the grid, there will be no tile there.

var mytileint = mytilemap.get_cellv(mytilemap.world_to_map($Player.position))
if mytileint and mytileint != null :

^ you can see what I am trying to do with the second line… I’m trying to say… if you didn’t get a tile… don’t do anything.

Can anyone take a peek at this for me?

(I’ve been in other positons like this… such as trying to return an inventory item of the players… same scenario… if the player doesn’t have the thing at the time, I get a null, and then the program crashes).

:bust_in_silhouette: Reply From: timothybrentwood

TileMap.get_cellv() returns ID_CELL = -1 if a cell isn’t found at the given position so my_tile_int will never be null.

is_instance_valid(instance: Object) is what you want to call to check for Nodes/objects if you’re crashing on objects that are freed from memory - this is likely an issue with you maintaining arrays of nodes that you should let the engine handle though. There is also object.is_queued_for_deletion() to check if something has been queue_free()'d this frame.

if object: is the same thing as saying if object != null:, similarly if not object: is the same thing as saying if object == null: - I personally like the way it looks than the ==/!= comparison.

Thank you very much Timothy.

mattkw80 | 2021-05-07 19:35