I’m new to Godot, but not to programming. Right now, I’m learning Godot with GDScript, but I plan on eventually programming in C++ using GDExtension.
I had a problem downcasting a 2DNode scene instantiated to the type declared in the attached script (using the as keyword). In a dynamically typed language, this is less of a problem since you can call the methods anyway, but what about statically typed languages like C# and C++, what happens there?
I saw in the scene type menu you have “extends,” but I couldn’t find the class in the script. Maybe I’m missing something.
Can you downcast the scene to the associated class in C# and C++?
If we can in statically typed languages, should we have a request to have it also in GDScript? I’m not sure it’s a high priority, though.
I just want to say that I’m grateful for the existence of this full-fledged open source game engine. It’s awesome!
@dbat, I realise that the script is a class, that’s why I was supprised I couldn’t downcast to that class.
classname Card # without this I get a compile error
.
.
. var c = _card_packed.instantiate(); add_child(c) var type_name = c.get_class() # returns "Node2D" var card: Card = c as Card # <--- fails, card is being set to null
@Moreus I already wrote in the question that due to the dynamically typed nature of GDScirpt, I can treat it like the derived class. There is an effort to make GDScript optionally typesafe; hopefully one day there will be a “strict typing” checkbox option in the setting that forces you into putting types on every variable.
Also without downcasting I’m loosing the ability to get “intellisense” completions.
At the moment there is a big bug-fix on to just get Godot to respect the class_name keyword in the first place, without a million startup errors every time.
Perhaps you can write “class_name YourClass” at the beginning of the script of the class you need after “extends YourClassNode”, then you can immediately create it in the “add node” function in the hierarchy and maybe this will help with your problem. It’s not a fact that it will work. Just a guess.
Sample code:
extends Node2D
The packedscene does have the card script attached to it. It even shows when I inspect the return value from c.get_script().
Thanks, @indicainkwell, the side notes are really useful info. I guess I
can also create a pseudo abstract class in c++, with the interface to be implemented in the gdscript, and use it as the base class for the gdscript node, if I really wanted to.