Skip to content

Writing Custom Logic

Want to create a flashlight, a grappling hook, or a magic spell? You can easily extend the system by writing your own ItemLogic script.

Step-by-Step Guide

1. Create the Script

Create a new GDScript that extends ItemLogic.

class_name FlashlightLogic extends ItemLogic

@export var spotlight_node_path: NodePath
var _is_on: bool = false

func on_primary_use(slot_index: int = -1) -> void:
    _is_on = !_is_on

    # Find the spotlight on the player
    var spotlight = _player.get_node_or_null(spotlight_node_path) as SpotLight3D
    if spotlight:
        spotlight.visible = _is_on

    # Optional: Consume battery durability
    if _is_on:
        _consume_item_durability(slot_index, 1)

    use_finished.emit(_item, true)

2. Handle Consumption

Notice the use of _consume_item_durability(slot_index, amount). This built-in helper automatically finds the player's InventoryComponent and reduces the item's durability. If break_on_zero is true on the item, it will destroy itself automatically!

If your item is consumed entirely (like a potion), use:

var inv_comp = _player.get_node_or_null("InventoryComponent") as InventoryComponent
if inv_comp:
    inv_comp.inventory.remove_item(_item, 1)

3. Assign to Item

  1. Open your ItemDefinition resource (e.g., flashlight.tres).
  2. Find the logic_script property in the Inspector.
  3. Drag and drop your new FlashlightLogic.gd script into that slot.

That's it! next time the player uses the item, your custom code will execute. ```