error: attempt to call function 'is_colliding' in base 'null instance' on a null instance

I've just started making a basic fps in the Godot engine, and I'm currently stuck on making a basic Raycast weapon. I've looked up tutorials from Coding With Tom, Gabaj YT, and multiple others, and yet no matter which one, I always end up writing the same piece of code:

if Raycast.is_Colliding:

and no matter how exactly I copy it down, I always end up with the same error:

error: attempt to call function 'is_colliding' in base 'null instance' on a null instance.

Upvotes: 1

Views: 3141

Answers (1)

Theraot
Theraot

Reputation: 40295

Raycast is a class. And is_colliding is one of its methods. But it is not an static method, you need an instance of Raycast.

Chances are, you do have an instance. If you have been following the tutorials, presumably you have a Raycast node in the scene tree added from the editor, and it is called… let me guess… Raycast. Yes, I do it too. Until it begins to be an issue and I rename it to something more meaningful or go for a different approach, but I digress.

The issue is that you are not referring the Raycast instance. You can reference nodes from your script using $, like this: $Raycast. It is a shorthand for using the get_node method. See Nodes and scene instances. To be clear, what you put after $ is the relative path on the scene tree, so it might not be just the name of the node. Here I'm assuming the node is a direct child of the node that has the script you are writing.

Thus, I would expect code like this:

if $Raycast.is_colliding():

Granted, you will see code that does look like this:

if raycast.is_colliding():

That is because somewhere in the script they have a line that looks something like this:

onready var raycast := $Raycast

Which declares a variable raycast and - on ready - sets it to a reference to the node, and then they can continue using that variable form there. With video tutorials some might skim over that. Here I found it on a Garbaj video on the topic: Godot FPS Hitscan Weapons Tutorial at 1:52

Upvotes: 1

Related Questions