0 votes

In the game I'm developing, I randomly select a number of enemies from an array, some of which may be chosen more than once. The issue is, I can't instance one scene multiple times, meaning only one ends up being instanced. Is there a way around this? Any help would be appreciated.

Godot version 3.2.3
in Engine by (103 points)

1 Answer

0 votes

Here's how I would do it:

var possible_enemy_scenes = [load("res://Enemy_A.tscn"), load("res://Enemy_B.tscn"), load("res://Enemy_C.tscn")]
var number_of_enemies = 20

func _ready():
    randomize()
    for enemy in number_of_enemies:
        var random_position = Vector2(rand_range(0, 720), rand_range(0, 720))
        instance_enemy_at_position(random_position)

func instance_enemy_at_position(pos : Vector2):
    var enemy_to_instance = choose_random_from_array(possible_enemy_scenes)
    var enemy_scene = enemy_to_instance.instance()
    enemy_scene.position = pos
    add_child(enemy_scene)

func choose_random_from_array(arr: Array):
    arr.shuffle()
    return arr.front()
by (3,711 points)
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 webmaster@godotengine.org with your username.