Search code examples
godotgdscript

Godot - Unexpected token: Identifier:"Function name"


I'm trying to make a wave game in Godot and I tried making for loops but I couldn't get them to work outside a function. But when I did put it in the function Godot won't recognize the function and give me this error - error(27,1): Unexpected token: Identifer:spawnEnemies

Code:

extends Node2D

var screenSize = get_viewport().get_visible_rect().size

func _ready():
    pass # Replace with function body.

var scene = preload("res://scenes/enemyInstance.tscn")

func _physics_process(delta):
    pass

func spawnEnemy():
    var instance = scene.instance()
    var rng = RandomNumberGenerator.new()
    var rndX = rng.randi_range(0, screenSize.x)
    var rndY = rng.randi_range(0, screenSize.y)
    instance.position.x = rndX
    instance.position.y = rndY
    add_child(instance)

func spawnEnemies(number):
    for i in number:
        spawnEnemy()


spawnEnemies(7)

I've tried removing the for loop or changing how the variables are but nothing worked.


Solution

  • GDScript does not support top level statements.

    Thus, this line is invalid:

    spawnEnemies(7)
    

    The error, in fact, is telling you that it didn't expect to find spawnEnemies there. It has nothing to do with a loop or variables.

    So, when exactly do you want that to execute? Given that your code requires to access the scene tree (it uses add_child) it cannot be when the object has just be initialized (i.e. in _init), it must also be in the scene tree. We have a method for that _enter_tree.

    Turns out there is one more wrinkle. If there are children defined from the editor, those have not been added yet in _enter_tree. Which might result in Godot saying that the node is busy. The error has this text: "Parent node is busy setting up children, add_node() failed. Consider using call_deferred("add_child", child) instead.".

    Thus, just use the _ready that the template gives you, unless you have a reason not to:

    func _ready() -> void:
        spawnEnemies(7)