0 votes

Alright, Godot wizards. I am working on a semi-random level loader for a game I am working on, using arrays to store level paths and then using a RandomNumberGenerator to pick one from the array, load that scene, and then remove it from the array and adjust the numbers to dodge errors.

Here's what I can't figure out - every time it loads the last item in the array (item with value equal to the array's size) the program crashes. (Example: if the array size is 6 and it loads level 6, it bugs out.) What am I missing?

Single global function, called on each scene.
(I understand this is not terribly efficient coding, appreciate any feedback there.)

extends Node

var nextScene
var removeTag
var levelKeyMax
var levelKeys = [

func _ready():
    levelKeyMax = levelKeys.size()

func levelSelect():
    levelKeyMax = levelKeys.size()
    if levelKeys.empty() == false:
        var rng = RandomNumberGenerator.new()
        var num = rng.randi_range(0,(levelKeyMax))
        nextScene = (levelKeys[num])
        removeTag = num
        print("Loading " + str(nextScene))

    if levelKeys.empty() == true:
Godot version 3.4.3
in Engine by (498 points)
edited by

1 Answer

0 votes
Best answer

SOLVED. I figured it out.

While the array has a size, the size is not the same size as the end of the index.
While the array has 20 elements, you don't call on the 20th element with array[20] - you call on it with array[19] because the first element is zero! D'oh!

A simple -1 to the levelKeys.size() and solved. Leaving it here for whoever else gets perplexed on this tiny detail.

func levelSelect():
     levelKeyMax = levelKeys.size() -1


by (498 points)

Rats, and I was just going to suggest that part. :-/ Glad you found it.

BTW, may I suggest reusing the RandomNumberGenerator object instead of creating a new one each time.

Ah! That’s a good point. I’ll substantiate that it outside the function/in a separate function next time. Good call!

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.