0 votes

I am creating a dispenser that should be able to spawn anything (enemies, power-ups, etc.)

Fo now, I have this code:

extends Node2D


export(float) var delay: float = 1.0
export(PackedScene) var dispense: PackedScene

func _ready() -> void:
    $Timer.wait_time = delay

func _on_Timer_timeout() -> void:
    var newElement = dispense.new() # This doesn't work

func _get_configuration_warning() -> String:
    if dispense == null:
        return "%s needs an element to dispense" % name
    return ""

The dispense attribute is the thing that is supposed to be emmited every delay seconds.

How do I instanciate a new element based on its type? I tried element.new(), but it doesn't work (Invalid call. Nonexistent function 'new' in base 'PackedScene'. when interpreted).

How do I instanciate it?

Godot version v3.2.3.stable.fedora
in Engine by (25 points)

2 Answers

+2 votes
Best answer

You need to use instance() method instead of new(). new() is for scripts, instance() is for nodes.

by (1,314 points)
selected by

Amazing, it works like a charm. Thanks!

0 votes

You need to create class in order to instantiate it using New().
Take script of your dispenser and define its class by classname keyword, followed by your chosen name, for example : classname dispenser, no more syntax. It should be first line of code right after "extends" keyword.

From this moment You can refer to this class from any script, You don't need to preload it or encrypt within variable. And this will be possible :

func _on_Timer_timeout() -> void:
        var newelement = dispenser(new)
by (2,432 points)

Nice to know, but it doesn't answer the question. I was looking for a way to instanciate a PackedScene, not the current class. AlexTheRegent answered my question perfectly.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.