• Godot Help
  • How to change an instanced scene's script through code

I am making a tower defense game and I made 1 tower scene with a script and everything necessary for it to function and made an AI script for each tower that extends the original script.

I want to change the tower's script from the base script to the corresponding variation when the player buys one.

I tried using the set_script() function like this:

onready var base_plant = preload("res://Plants/Plant Roster/BasePlant.tscn").instance()

func _ready() -> void:
	base_plant.set_script("res://Plants/Plant Roster/Peashooter/Peashooter.gd")

but it said: Invalid type in function 'set_script' in base 'Area2D (BasePlant.gd)'. Cannot convert argument 1 from String to Object.

what is the correct way of using the set_script() function, or what other method should I use?

  • Script is a Resource type, not a String. If your class has a name (using class_name), then you can try this:

    base_plant.set_script(Peashooter)

    or you can do this:

    base_plant.set_script(load("res://Plants/Plant Roster/Peashooter/Peashooter.gd"))

Script is a Resource type, not a String. If your class has a name (using class_name), then you can try this:

base_plant.set_script(Peashooter)

or you can do this:

base_plant.set_script(load("res://Plants/Plant Roster/Peashooter/Peashooter.gd"))