godotengine / godotengine/godot
inconsistent behavior with get_global_class in GDScript
- Dominant language
- C++
- Stars
- 117k
- Forks
- 26.8k
- PR merge metrics
- PR metrics pending
Description
### Tested versions
- Reproducible in 4.6, 4.5.1
### System information
Godot v4.6.stable - Windows 11 (build 22621) - Multi-window, 1 monitor - OpenGL 3 (Compatibility) - NVIDIA GeForce RTX 3050 Laptop GPU (NVIDIA; 32.0.15.8132) - 12th Gen Intel(R) Core(TM) i5-12500H (16 threads) - 15.69 GiB memory
### Issue description
[This post on Reddit](https://www.reddit.com/r/godot/comments/1ossfv2/comment/nnzhpbe/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button) shares that you can get the name of a custom class with:
``(MyClass as GDScript).get_global_name()``
However, simply typing ``MyClass.get_global_name()`` won't build because it's not a static function and needs an instance.
My report refers to _why would type casting add functions not there previously?_ I'm not sure what type the class name is when typed by itself in the script editor, but the [documentation](https://docs.godotengine.org/en/4.6/tutorials/scripting/gdscript/gdscript_basics.html#casting) does say:
> Casting between object types results in the same object if the value is of the same type or a subtype of the cast type.If the value is not a subtype, the casting operation will result in a null value.
Is the ``as`` keyword behavior correct here? And why couldn't this function call just exist on the object normally?
My use case isn't covered by ``is_instance_of`` because I want to make a dictionary indexed by class names. Adding items is easy as I have the instance to call ``get_script().get_global_name()`` from, but not when checking if those values exist in the dictionary. I also can't create instances as needed, as creating instances of a class may need extra params as there aren't multiple constructors.
(sorry if the title isn't descriptive enough or if it should be a proposal, I'm very confused by the behavior and if it's intended or not)
### Steps to reproduce
Make a custom script (here named my_class.gd) with a class_name (here named ``MyClass``).
Make a script to print the class name like so:
``print((MyClass as GDScript).get_global_name())``
You should be able to run and "MyClass" will appear on the console.
Now make the script print the class name from the static class, like so:
``print(MyClass.get_global_name())``
You should see the following error as soon as you save the script: **_Cannot call non-static function "get_global_name()" on the class "MyClass" directly. Make an instance instead_**
### Minimal reproduction project (MRP)
[class-name-gdscript.zip](https://github.com/user-attachments/files/25217741/class-name-gdscript.zip)
Contributor guide
Assessment
This issue has not been assessed yet.