Using an Array to select a sprite/texture

v4.2

What I’m trying to do is make it so that when I add this scene to a tree, it picks a random texture from an array. So far, I haven’t been able to even get it to select from the array. What am I doing wrong?

Here’s the code:

extends Node2D
var sweet_berries = “res://sweet-berries-sprite.jpg”
var bread = “res://bread-sprite.jpg”
var orders = Array([sweet_berries, bread])
func _ready():
var current_order = orders.pickrandom()
if current_order == sweet_berries:
print(“Sweet Berries have been ordered!”)
if current_order == bread:
print(“Bread has been ordered!”)

Do you get an error? Seems like you should since the function is pick_random() not pickrandom(), otherwise it should work.

Make sure to format your code pastes properly

I’d be tempted to rearrange this a bit:

extends Node2D

const sweet_berries = "res://sweet-berries-sprite.jpg"
const bread         = "res://bread-sprite.jpg"

var orders = [sweet_berries, bread]

func choose_order():
    match(orders.pick_random()):
        sweet_berries:
            print("Mmmm, berries.")
        bread:
            print("Oooo, bread.")

func _ready():
    choose_order()

If you’re going to have a bigger list, I’d be tempted to make it more data driven:

extends Node2D

var orders: Array = [
    { "res": "res://sprites/sweet-berries.jpg", "action": order_sweet_berries },
    { "res": "res://sprites/bread.jpg",         "action": order_bread         },
    { "res": "res://sprites/custard-tarts.jpg", "action": order_custard_tarts },
]

func choose_order():
    var order = orders.pick_random()
    var action = order["action"]
    action(order)

func order_sweet_berries(order: Dictionary):
    print("Ordering sweet, sweet berries...")
    print("    resource is " + order["res"])

func order_bread(order: Dictionary):
    print("Ordering tasty, tasty bread...")
    print("    resource is " + order["res"])

func order_custard_tarts(order: Dictionary):
    print("Ordering delicious, delicious custard tarts...")
    print("    resource is " + order["res"])

You could potentially put a lot more information in the dictionaries nested in orders, enough that you could just call a single generic function instead of having the per-entry specific functions.

1 Like

This was the problem as I discovered shortly after posting this LOL. Thanks for the help!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.