Can you infer a class type onto a node just for type hinting?

Godot Version: 4.5-beta4

Hi! For specific reasons, I would like to develop my game without classes but by extending scripts of scenes.

Basically, instead of:

# player.class.gd
class_name Player
extends Node

# player.gd
extends Player

Do:

# player.class.gd
extends Node

# player.gd
extends "res://player.class.gd"

It works exactly as a class definition except you don’t get to instantiate nodes as your class and you cannot use it as a global name on other scripts, meaning you can’t:

func _on_player_joined(player: Player) -> void:
	return player.name

as it would give an error: Error at (1, 30): Could not find type "Player" in the current scope.

Still, you can just remove the assignment:

func _on_player_joined(player: Node) -> void:
	return player.name

and it would work just fine because Godot allows duck typing.

My question is: is it possible to define a class separate to the scene that’s actually going to be used, but with the same properties and infer that onto the classless node? As much as I need this feature for my plans to work, I would not like to loose type hinting for it.

From my quick testing, I’ve found out it’s not possible to infer a class type onto a node that does not share the class. Both assigning the type for the variable and inferring it onto the node with the keyword as result in errors.

Nope, you can’t do that AFAIK.

Right now I’m really wishing GDScript supported multiple inheritance. There’s been more than once where I’ve made a generic object that I want to inherit properties of Node2D, Node3D or Control but keep all the underlying properties the same. So far, I’ve always found an alternate solution.

As for what you’re trying to do, the first thought I hade was create an Autoload factory. Pass everything as a Variant or Node, and when you want it to b a thing, have the factory construct it anew.

For your specific Player example, in multiplayer what I do is have two methods: to_dictionary() and from_dictionary() that convert my object for passing through an RPC call.

1 Like

You can preload a script and use it as a type

const Rifle = preload("res://player/weapons/rifle.gd")
var my_rifle: Rifle
3 Likes

Hehe!!! Gosh, I’ve been over that page countless times and it’s so simple. Guess we always find ways to overcomplicate things :sweat_smile:. Thanks! :blush:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.