+1 vote

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.getcellv(mytilemap.worldto_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).

Godot version 3
in Engine by (117 points)

1 Answer

0 votes
Best answer

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.

by (3,479 points)
selected by

Thank you very much Timothy.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.