Class variables can't be referenced from another script

Godot Version

Godot 4.6.1.stable

Question

I have a script that tracks the position of the node it’s attached to. I am trying to reference said position from a different script. This isn’t working. I feel like I am missing something very simple, because I’m pretty sure I have done this before in the exact way I’m trying to do it now, and it worked fine.

The tracking script has been pasted in full, the referencing script is just the part that interacts with it.

Tracking script:

extends Node3D
class_name anchorpoint

var anchor : Vector3

func _physics_process(delta: float) -> void:
	anchor = self.position

Referencing script:

extends CharacterBody3D

func _physics_process(delta: float) -> void:
	look_at(anchorpoint.anchor)
	print(anchorpoint.anchor)


This returns the following errors:

ERROR: res://scripts/player.gd:17 - Parse Error: Cannot find member “anchor” in base “anchorpoint”.
ERROR: res://scripts/player.gd:18 - Parse Error: Cannot find member “anchor” in base “anchorpoint”.

To my knowledge, this is how you’re supposed to cross-reference scripts without hassle. I’m assuming I’m missing an extension somewhere or I’ve made a typo, but I’m failing to see where I’ve gone wrong.

I’m using this system to orient the player model in the direction of the camera; essentially locking the player’s facing to a physical crosshair. There are other ways of doing this that are probably better, but right now I am exploring the limitations of this specific method of camera control.

You need to reference a node the script is attached to, not the script class itself. You’re currently doing the latter because anchorpoint is the script class name.

2 Likes

Thank you, knew it was something simple I was missing. I’ve updated the player code to this:

extends CharacterBody3D

@onready var anchornode: Node3D = $Camera/Front_anchor

	look_at(anchornode.anchorpoint.anchor)
	print(anchornode.anchorpoint.anchor)

While this is referencing the correct node now, it’s now returning this error:

E 0:00:00:426   _physics_process: Invalid access to property or key 'anchorpoint' on a base object of type 'Node3D (anchorpoint)'.

Previously, Godot was able to find the class but not the variables inside it, and now it’s able to find the node, but not the class in the script attached to it. anchornode.[script name].anchorpoint.anchor also doesn’t work.

Edit: scene tree and scripts list, for reference:

You don’t want to use the script name here. Just get a valid reference to the node like you did with anchornode and use the dot syntax to access its property: So: anchornode.anchor

1 Like

Okay, thanks again, this code works fine now. Well, I say “fine”, now the code has new problems, but I think I know how to fix those ones.