Change which objects you can click to add in-game

Godot Version

4.2.2.stable

Question

Hello, I currently am working on a 2D game where you can plant certain items (trees, flowers, etc) by clicking on the screen.

I already have figured out how to click and add one kind of item onto the screen via input mapping and instancing.

I am looking to take it one step further and add more options of items that you can plant, by clicking on the name of the item in a list (aka “selecting” it) and now whenever you click, you now plant the new item you currently have selected.

How can I achieve this?

You should have a variable where you store what you want to spawn when clicking.

At first you can make a system where pressing a key changes the active item. e.g. when “2” is pressed you set item_to_spawn = “birch_tree”. Then you could have a dictionary of items where you store the items and scenes.

var items = {
    "birch_tree": preload("res://birch_tree.tscn"),
    "bush": preload("res://bush.tscn"),
    # and so on
}
var item_to_spawn = "birch_tree"

func _process(delta):
    if Input.is_action_just_pressed("1"):
        item_to_spawn = "birch_tree"
    elif Input.is_action_just_pressed("2"):
        item_to_spawn = "bush"
    # and so on

func spawn_item(position):
    var item_instance = items[item_to_spawn].instantiate()
    # set location etc
    add_child(item_instance)

You can worry about building a UI for it later once you have the simpler version working :slightly_smiling_face:

This worked great, thank you!

1 Like

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