GDScript Help for Static Typing

Godot Version

Godot 4.4

Question

Can we assign multiple data type to one variable ? Like

var my_variable : Canvas_Item or Canvas_Class_Item

where I created a variable and assign them two classes one is Canvas_item and other is Canvas_Class_Item.

Or like this one as well

var object : StaticBody2D or CharacterBody2D or may be somthing like that ?

You can’t do it specifically like you mentioned, but you can use a Variant type instead - in such a case, you can feed any class into that variable.
Or depending on the structure of your classes, you can make them inherit the same base abstract class and then use that abstract class in your variable declaration.
e.g. both StaticBody2D and CharacterBody2D inherit from PhysicsBody2D

PhysicsBody2D
Inherits: CollisionObject2D < Node2D < CanvasItem < Node < Object
Inherited By: CharacterBody2D, RigidBody2D, StaticBody2D

so your variable could be

var object: PhysicsBody2D

and this will allow you to feed CharacterBody2D, RigidBody2D or StaticBody2D into that variable.
You can do the same with your class structure and use inheritance.

2 Likes

ok i understand this. But is there a way i can mimic such kind of behaviour without mentioning thier common ancester. because if we mention them then still godot have to find the type of class at run time to find it’s data. making it static was whole point is too avoid runtime load.
What you think about this?
Thanks for repley. :innocent:

“One of two options” is more or less the same runtime cost as “one of many options”.

2 Likes

If performance is your concern - then I would advise you to not worry about it, unless you encounter some specific bottle neck with this. There are way worse performance-sinks in the engine than this.

2 Likes

okay that’s interesting.
Thanks mate