0 votes
extends Node2D

var fN = ["Michael ", "Malcolm ", "Mason ", "Matthew ", "Marty ", "Marshall "]
var lN = ["Green", "Gatry", "Gunther", "Grey", "Geller", "Galloway"]

func genPlayers(amount):

    for n in range(amount):
        var player = {
            "name": fN[randi() % fN.size()] + lN[randi() % lN.size()],
            "age": randi()%10+18
        }
        return player

func _ready():
    randomize()
    print(genPlayers(15))

As you can see here, I'm trying to randomize 15 random people, with a randomized name and age. Using genPlayers(15)I call for a randomized name and age 15 times. However, when it gets printed from print(genPlayers(15)), it only prints one person:

enter image description here

Why is this happening? If I do print(player) from inside the function, it prints all 15. But returning the player value and then printing it in the _ready() function is only printing 1.

asked Jul 1 in Engine by Zakuree (12 points)

1 Answer

0 votes

Return causes a function to cease operating and go out of scope after handing off the value it's returning.

Consider wrapping your actual "generator" in a function that repeatedly calls the generator based on an int value you feed to the wrapper function.
EDIT: you would need to initialize an empty array at the top of the wrapper, then push_back each person generated to the array. Return the array.

answered Jul 1 by DDoop (395 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 How to use this Q&A? before posting your first questions.