Hello folks, hoping someone has a method that can help me with my madness.
So I have a custom resource that is an item, this resource has 4 different textures that I set in the editor, code looks like this:
@export var texture: Texture2D @export var texture2: Texture2D @export var texture3: Texture2D @export var texture4: Texture2D
I load this resource into the game using a scene called “slot”, this slot displays the texture I assigned and other info on the item.
Question: how can i get the slot to randomly display one of the textures when it is loaded in? Additionally, how can i check if there is a texture set before i display it? My best guess would be to write a complex if statement to check if there is a texture, then use a random variable to decide what texture to display?
Anyway, thank you in advance for any suggestions.
So, I assumed from the name of the scene being “slot” that you were referring to a slot machine game, so the code is a little more elaborate than what you asked for because I tried to make a grid system for this type of game, because of that, the parts that contain an answer to what you asked are below a comment.
extends Node2D
# This variable creates an array of paths for the sprites.
@export_dir var sprite_folder_paths: Array[String]
# The rest of the variables are related to the slot game.
const SPIN_UP_DISTANCE = 100.0
var reels := 3
var tiles_per_reel := 3
@onready var tile_size := get_viewport_rect().size / Vector2(reels, tiles_per_reel)
var extra_tiles := ceili(SPIN_UP_DISTANCE / tile_size.y) * 2
var rows := tiles_per_reel + extra_tiles
var slot_sprite
var slots := 3
var grid := []
var tiles := []
func _ready():
print("Extra Tiles: ", extra_tiles)
print("Rows: ", rows)
print("Tile Size: ", tile_size)
for col in slots:
grid.append([])
for row in 3:
# Defines the position of each slot within the array grid.
grid[col].append(Vector2(col, row-0.5*extra_tiles) * tile_size)
_add_tile(col, row)
func _add_tile(col :int, row :int) -> void:
# Creates a Sprite2D node within the scene, this will repeat until the for loop ends.
slot_sprite = Sprite2D.new()
"""
Loads a random texture for the created node (note that computers are not capable of generating True RNG,
only Pseudo-RNG, so you will probably need to make this part more complex to have a more balanced RNG,
I recommend watching the video at the end of this post to better understand this).
"""
slot_sprite.texture = load(sprite_folder_paths.pick_random())
# Centers the sprite correctly
slot_sprite.centered = false
tiles.append(slot_sprite)
var tile = tiles[(col * rows) + row]
tile.position = grid[col][row]
call_deferred("add_child", slot_sprite)