Help with accessing Raycast3D colliders

Godot Version

Version 4.2.2

Question

I’m pretty new to Godot and I’m making a very simple shooting mechanic involving a raycast and a target. The target has a health variable in it’s script, which is exported and therefore appears as a property:

extends Node3D

@export var health = 5

func _process(_delta):
if health <= 0:
queue_free()

But when it comes to accessing this health variable through the get_collider() function, i keep getting this error:

"Invalid get index “health” (on base: "Staticbody3D).

This is the code i’m using to access it:

extends Node3D

@onready var gs = $Player/Camera3D/Gunsight

func _process(_delta):
var target = gs.get_collider()
if Input.is_action_just_pressed(“leftclick”):
if target:
target.health -= 5

It might also be useful to mention that the raycast and the target are on their own collision layer/collision mask and so can only collide with one anoher. I’ve tried looking the problem up, but every existing thread i’ve found has done it seemingly the same way without problem, so I’d be very grateful for any help. Thanks.

your “target”-script extends a node3D, but the collider is a staticbody3d. Something isnt right here, either it collides with something else or your “target”-script is wrong

Your code looks fine - however there might be something set incorrectly with your collision layers.

If you have the static body on layer 3 the collision mask of the raycast must also be set to collide with layer 3.

He claims that this is already done

Yes, i forgot to mention that the target is a instance of another scene, which has a staticbody as a child of a node3d (the node3d which the script is attached to). I have now changed this so the script is attached to the staticbody and extends from it too. It works now. thanks you very much.

1 Like