Can I write a script that randomly selects between multiple scenes?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Nyx

So I’m following the “building your first game” tutorial in Godot, and the way they instruct you to do things has you assigning the exact same collision shape to several sprites despite the fact that one sprite in particular has wildly different proportions

So, being the overachiever that I am, I decided I would make separate scenes for each type of mob and their sprites so I can assign them unique collision capsules

That being said, I’m at a bit of a loss now. All of the sprites being under the same scene allows the tutorial person to write a single script that picks a sprite at random. I can’t do this because, again, they’re in separate scenes.

It seems like I either need to figure out a way to get them all in the same scene while keeping them independent from each other, or I need to find a way to randomly pick between separate scenes, both of which are just a little bit beyond me. Any help would be much appreciated

:bust_in_silhouette: Reply From: jgodfrey

Sure, you can do that. Really, you just need to 1) load a scene, 2) create a new instance of it, 3) position it in space, and 4) add it to the scene tree. Here’s a quick and dirty example:

extends Node2D

var scenes = [] # an array to hold all of the scenes

func _ready():
    # preload all of the scenes (how ever many you have)
	scenes.append(preload("res://Child1.tscn"))
	scenes.append(preload("res://Child2.tscn"))

    # randomly spawn one of the scenes
	spawn_scene()

func spawn_scene():
    # select one of the scenes at random, and create an instance of it
	var scene = scenes[randi() % scenes.size()].instance()

    # set the position of the new instance
	scene.position = Vector2(100, 100)

    # add the new instance to the scene
	add_child(scene)

Thanks for the help! Just for clarification, where should that script be written? I’d imagine the main scene, but the scene the tutorial instructs you to make the main scene is the player scene, and it seems bizarre to have this code in the player scene.

Edit: Actually, after looking further ahead, it seems the player scene does not remain the main scene. I’ll see what I can do and how I can mess around with things. Thanks again for the help!

Nyx | 2020-07-15 18:30

I haven’t tried to cross-reference your description with the tutorial in question, but from your original statement:

All of the sprites being under the same scene allows the tutorial person to write a single script that picks a sprite at random

You should be able to replace the code that “picks a sprite at random” with something like the above. So, I’d think the posted code likely belongs in the same script where that’s happening in the original tutorial…

jgodfrey | 2020-07-15 19:25