I have a scene called Planet and a script like that:
1. extends Node2D
2.
3. @export var radius: float
4.
5. func collide(other:Node2D):
6. if other is Planet :
7. if(radius > other.radius):
8. print("I win")
9. else:
10. print("I loose")
11. else:
12. print("Not a planet")
The line 6 gives me an error Could not find type "Planet" in the current scope.
How do I do these kinds of tests where I check that a scene object is of particular type(current scene's type)?
Also, is it possible to specify a parameter type (line 5) to a particular scene? Smth like
func collide(other:Planet):
I know, it doesn't change much since the language is dynamically typed. But that would help with documentation and maybe autocomplete.
GDScript type "hints" are hints. They are actually type declarations, and they are enforced in runtime. GDScript is a progressively typed langauge, meaning that you can start programming fully dynamically and then steadily add static typing, up to a point, so it is not fully dynamic and not fully static.
There are two ways the syntax other:Planet
will work:
You can add a class_name
to the plane script, at the top:
class_name Planet
# Planet Code
Then in other scripts you can use obj:Planet
.
You declare a constant set to preloading the script, also at the top, but on the script that uses it:
const Planet = preload("res://path/to/planet/script.gd")
# Code that uses Planet and has stuff like obj:Planet in it
As per checking the type in runtime...
First, if you have a variable and you have no idea what kind of thing it has, you can use typeof
. And that will return a constant from the enum Variant.Type
, in this case I expect it to be TYPE_OBJECT
.
And second you can check the class of an object if the is
operator, like this obj is Planet
.
However, if you do not know the class and you want to find it out. Then try to get the script of the object with obj.get_script()
.
If it has a Script
, up until Godot 4.2.x you need to iterate over ProjectSettings.get_global_class_list
to find the name of the class, if it has any. From Godot 4.3 onwards you will be able to use script.get_global_name()
.
On the other hand, if the Object
has no Script
, then its class is obj.get_class()
.