Random Enemy Generator

Godot Version

4.6.3

Question

I’m making a random enemy generator, and there’s a weighted chance that it’s more likely to be an easy enemy than a hard one. I’m not sure why, but the enemy_chosen variable is never the hard one. It’s obviously something with my code, but I’m quite new to Godot, so i dont really know much about this. Here’s my code. Thanks

extends AnimatedSprite2D


var rarities = {
	"Easy": 1000,
	"Hard": 350,
}

var rng = RandomNumberGenerator.new()
var enemy_chosen 

var easy_enemy_scene: PackedScene = preload("res://Scenes/Hostiles/easy_enemy.tscn")
var hard_enemy_scene: PackedScene = preload("res://Scenes/Hostiles/hard_enemies.tscn")
@onready var enemy_spawn_pos: Marker2D = $EnemySpawnPos

func _ready() -> void:
	for n in 100:
		print(get_random_enemy())

func get_random_enemy():
	rng.randomize()
	
	var weighted_sum = 0
	
	for n in rarities:
		weighted_sum += rarities[n]
	
	var item = rng.randi_range(0, weighted_sum)
	
	for n in rarities:
		if item <= rarities[n]:
			return n
		item -= rarities[n]
		enemy_chosen = n






#
#func _process(delta: float) -> void:
	#pass


func _on_frame_changed() -> void:
	if frame == 5:
		get_random_enemy()
		if enemy_chosen == "Easy":
			print("spawn easy")
			var easy_enemy_isnt = easy_enemy_scene.instantiate()
			add_child(easy_enemy_isnt)
			easy_enemy_isnt.global_position = enemy_spawn_pos.global_position
		elif enemy_chosen == "Hard":
            #This never triggers, and i've tried multiple times, so i doubt it's just RNG
			print("spawn hard")
			var hard_enemy_isnt = hard_enemy_scene.instantiate()
			add_child(hard_enemy_isnt)
			hard_enemy_isnt.global_position = enemy_spawn_pos.global_position

return n means the function is ended early, enemy_chose will not be set after the return. Preferably you would not use this enemy_chosen variable inside of the function at all, instead storing the result of the function.

func _on_frame_changed() -> void:
	if frame == 5:
		var enemy_chosen := get_random_enemy()
		if enemy_chosen == "Easy":

hi can we be a team

l can help when needed

Thanks again! It works great!

sure, that would be good