godot: Cannot convert self to subclass in the code editor
Godot version
3.4.3.stable
System information
win7, gles3
Issue description
Cannot convert self
to subclass in the code editor, but others can
Steps to reproduce
Normal conditions:
class Super:
pass
class Sub extends Super:
pass
var super:Super = Super.new()
var sub:Sub = super as Sub
self
conditions:
extends CollisionObject2D
var this:KinematicBody2D = self as KinematicBody2D # This will result in an error tip in the code editor
# var this:KinematicBody2D = self as CollisionObject2D # no error
func _physics_process(delta: float) -> void:
...
push_velocity = this.move_and_slide(push_velocity)
...
Minimal reproduction project
No response
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 15 (9 by maintainers)
I am now using the following code snippet, which can be run(This problem doesn’t have much impact on my current project):
I just want to add some common attributes to all types of collision bodies. I think this is very common
TBH I still think that attaching a script to an object of a different type shouldn’t be allowed. It’s currently used by users as a hack but I don’t see it as a good practice. In that sense, the casting
self
wouldn’t be usefulEven if you can cast
self
, it gives many other errors if you try to access methods and properties from the actual object when is different from the class you extended. So it’s super bothersome to use even if we remove the casting errorI can make it work as expected with the following, but silly, code:
This also applies to
self is KinematicBody2D
.I think this needs reopened and looked at. Perhaps these errors (in the self comparison case) can be downgraded into warnings?
This is not a bug. It should not allow to convert base class object into a subclass object. It’s against OOP principles. It’s allowed to do vice versa – to convert subclass object into a base class object.
The behavior with conversion of
self
described above is correct. There is an issue with the first example:In that case the variable
sub
becomesnull
and this is expected behavior (see documentation for static typing).Conversions form base class variables to a subclass is allowed only if the base class variable is actually referencing to a subclass object. For example, this would be a valid case:
@Calinou I believe this issue can be closed.
You can run the Godot binary with the
--rendering-driver opengl3 --single-window
command line arguments to use the experimental OpenGL renderer (currently 2D-only). Note that this will not carry from the project manager to the editor automatically, so you’ll have to open a project directly using the command line for this to work.