Class not found

Godot Version

Godot 4

Question

Identifier “class_name” not declared in the current scope

For some reason this error just occurs randomly and says that the class_name is not declared when it worked perfectly fine before. I found that just rewriting the class_name line on the top of the script with the class fixes the error in the other scripts, but how can I prevent this error in the first place?

for example, when I declare a variable like
var x : class

and in another script I have
class_name class

sometimes it just stops working and shows this error message

Identifier “class_name” not declared in the current scope

class_name and extends have to be placed before all other script members, that’s just how the GDScript syntax is, you can’t change that.

When you say “class” it’s just a placeholder, right? because the word “class” is a reserved word in Godot (you can’t use it as a class name).

Here’s an example on how to do it:

class_name AnotherClass extends Sprite2D #or whatever you want to inherit from

var custom_variable = 5

func _ready():
	print("custom variable = " + str(custom_variable))

This is the main class of your scene.

class_name MyClass extends Node

var ac : AnotherClass

func _ready():
	ac = AnotherClass.new()
	ac.custom_variable = 8
	add_child(ac)

Then add the MyClass script to a node on your scene.
image

And here’s the result:
image

Yes, class is just a placeholder name, but you misunderstand my issue.
The issue is that for example, in your main class script the
var ac : AnotherClass
would just have the error that I described (Identifier “AnotherClass” not declared in the current scope), despite me not changing any code regarding the class at all.
To fix it I just had to redeclare the class (rewriting class_name AnotherClass in its script), but I want to prevent the issue in the first place