Assign child class to variable of parent type

Godot Version

4.5.dev5

Question

I have a class Obstacle with 2 children:CarObstacle and LogObstacle.
I want to assign one of these two children to a variable, but i can’t know at this time which of the two the obstacle will be. My assumption was that i could set this variable’s type to Obstacle and then clarify on _init e.g.

var spawner_object:Obstacle

func _init() -> void:
    spawner_object = LogObstacle

to my understanding, this would work in most object oriented languages given Logobstacle inherits from Obstacle, but when i try to run it i get the error "Value of type "LogObstacle" cannot be assigned to a variable of type "Obstacle".

is this just not something you can do in Godot or am i just doing it wrong?

Thanks !

when i type cast to a derived type i use this for example

func give_health( player:CharacterBody3D ):
    (player as PlayerBody3D).health = 50

so maybe you could try

func set_spawner(log_obstacle : LogObstacle):
    spawner_object = (log_obstacle as Obstacle)

I haven’t tested this, just an idea

This is correct assumption and will work with GDScript as well.

You get an error, because LogObstacle is a type, not an Object. You can’t assign a type to a variable that expects an Object. Your code will probably work if you create a new object with LogObstacle.new() like that:

var spawner_object:Obstacle

func _init() -> void:
    spawner_object = LogObstacle.new()
1 Like

Right, of course.
I appreciate the correction.

2 Likes

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