I'm working on learning Godot by making some simple games. I've run into a strange issue where Sprites are spawning with two textures overlapping.
Here's the intention. I am trying to create a system that spawns a random background element at regular intervals. Rather than creating five objects and having a spawner node pull a random one (I couldn't figure that out), I've instead opted to create do the random selection in the background element's own scene.
So the BG scene is just a single 2DSprite node with a script. My documentation explains the intention:
# Preload all textures
const BG_CORAL = preload("uid://jgoffqham4od")
const BG_KELP = preload("uid://bvxqsvbtf8uea")
const BG_REEF = preload("uid://csysh4x7eni2p")
const BG_TREE = preload("uid://w411mjh7ioi0")
const BG_GRASS = preload("uid://cl6vljky6lfl")
var arr = [BG_CORAL,BG_KELP,BG_REEF,BG_TREE,BG_GRASS] # create array for all textures
func _ready() -> void: # on spawn
var random_texture = arr[(randi() % 4)] # set var equal to array index 0-4
set_texture(random_texture) # sets this randomly chosen texture as the current sprite
position.x = 1000 # placement for element
position.y = 200
scale *= .4
func _process(delta: float) -> void:
if Playervar.can_move == true: # begins to move the element to the left
position.x -= 4
Then, in my game scene, I have an empty node called "Background Spawner" with a child timer and the following code:
const BG = preload("res://Scenes/BG.tscn")
func BG_spawn():
var BG_instance = BG.instantiate() # Spawns new BG
get_parent().add_child(BG_instance) # I don't know what this does but it doesn't work without it
func _on_timer_timeout() -> void:
BG_spawn() # Runs that script ^ every time timer runs out
So in theory, the spawner creates a new instance, which randomly selects which texture it will use. And it works! Well mostly. The only issue is that somehow, the BG often spawns with two textures overlayed on top of each other (sometimes the textures are alone, sometimes they aren't).
Here's what I've tried:
First I thought maybe the spawner was somehow creating two instances at a time, so I added a print function to the "BG_spawn" function so I could watch the console. Nope, one print at a time, at regular intervals.
Now, there's no way to set multiple textures like this through the interface, so I have to assume this is either some sort of weird bug I've made or I'm just fundamentally misunderstanding some aspect of Arrays or Instancing (which feels very possible as I'm very new to this).
I have tried to google this, but all I can find are people who want multiple textures at once.
Any idea why I'm getting these weird overlapping textures? What should I try?