+1 vote

Hiya! I have a problem instancing "enemies" for my platformer.
I have a scene for the level and another scene for the enemy (which is a KinematicBody2D); I'm trying to use a Path2D to spawn several enemies. Here's the code:

extends Node2D

signal restarting

export (PackedScene) var Enemy
export (int) var total_enemies = 0

# Called when the node enters the scene tree for the first time.
func _ready():
    var pos_curve = $EnemyPositions.get_curve()
    total_enemies = pos_curve.get_point_count()
    for i in range(0, total_enemies):
        var enemy = Enemy.instance()
        add_child(enemy)
        enemy.position = pos_curve.get_point_position(i)
        enemy.startPositionX = enemy.position.x
        enemy.startPositionY = enemy.position.y
        enemy.directedToRight = true

When I run the code, I receive the message in the title, referred to this line:

var enemy = Enemy.instance()

What's the problem?
Thanks in advance!

in Engine by (13 points)

1 Answer

+3 votes

That is telling you that Enemy has no value, and therefore instance() can't be called on it. When you declare the variable at the top like this:

export (PackedScene) var Enemy

You haven't given it a value. You need to select it in the Inspector (it shows up there because you used export) and assign the .tscn file you want. You can either click the Inspector field and choose "Load", or drag the scene file from the Filesystem dock and drop it on the property in the Inspector.

Doing that is equivalent to declaring it directly like this:

var Enemy = load("res://some_scene_file.tscn")
by (22,071 points)

Ok, now I modified it and it works. Thank you very much!

Which of those two ways of doing it is better?

Neither is "better". It's just two different ways of getting the same result.

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 Frequently asked questions and 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 [email protected] with your username.