godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.13k stars 92 forks source link

Add a scene path optional argument for class_name statement #10072

Open jumpy-lion opened 3 months ago

jumpy-lion commented 3 months ago

Describe the project you are working on

A tower defense game with different kinds of weapons.

Describe the problem or limitation you are having in your project

If a class is dependent on its child node, the new() function will not return a valid instance of the class. We need to use PackedScene.instantiate() method, which is not type-safe. Additionally, if the location of that scene is changed, all scripts that use the hard-coded path to that scene must be changed.

Describe the feature / enhancement and how it helps to overcome the problem or limitation

Adding an optional scene path parameter to the class_name statement would provide a type-safe way to create an instance of that class at runtime and reduce the occurrence of the hard-coded path to only one script.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

class_name FireMissile("res://path/to/fire_missile.tscn") extends Missile Then, an instance of that class could be created like this (assuming we don't want to change the new() functionality) var missile = FireMissile.from_default_scene() instead of var missile = load("res://path/to/fire_missile.tscn").instantiate() as Missile

If this enhancement will not be used often, can it be worked around with a few lines of script?

Using the @export annotation helps avoid issues with changing the scene's location, but it still doesn't guarantee that the scene is of the desired class. @export var missile_scene : PackedScene ... var missile = missile_scene.instantiate() as Missile

Is there a reason why this should be core and not an add-on in the asset library?

It's a language feature.

dalexeev commented 3 months ago