Any way to make something happen on interact?

Godot Version

4.6

Question

Helloooooo :3

My interact script for interactable objects is at the bottom, but! I was wondering, for my inventory, if i could make something happen on an interaction. If i can make something happen only after the object is collected, and the inventory can check that, than i can make my inventory because i can just make the script not work if that object isnt there right? :smiley:

(Ive been trying to make an inventory for a week lol)

extends StaticBody3D

func interact():
	print("interacted")
	queue_free()

(This collectable is also in an ā€˜interactable’ collection if that matters)

Absolutely!

There are a number of ways, my favorite is via events.
Here’s how I work with a ā€œpickup/collectionā€ type item.

Step 1: Collision test
(trimmed for clarity)

func _onBodyEntered(_body): # I do this for body and area both, they're identical
	if (PlayerOnly):
		if (_body.is_in_group("PLAYER")):
			emit_signal("onEntered", TriggerName, Type, self)
			_notifyPlayer()
	else:
		emit_signal("onEntered", TriggerName, Type, self)
	pass 

func _notifyPlayer():
	match Type:
		Persistent.TriggerType.COLLECT:
			# Here you can take some action on the player, or in a persistent object
			self.queue_free()
			pass
	pass

Step 2: Event bubbling
signal onEntered(TriggerName, TriggerType, Area3D)
signal onExited(TriggerName, TriggerType, Area3D)

The signals are what you would then listen for (used by the emit_signal above)

Step 3: Actions
PlayerData.collectionEvent.connect(_updateJob)

Connect is how you would connect to a signal in code, vs via the UI. _updateJob here is the func that is run when the event happens.

/edit - expanding on ā€˜inventories’
A nice way to handle an inventory is to have your player data in a persistent, and then you can use a dict type object to list the sorts of things you collected. Like this:

var ActiveJob = {
	0: {
		"shipper" = "",
		"mass" = 0,
		"dest" = "",
		"checkpoint" = ""
	}
}

If you load collectables via an external source (like a save file or something) you can actually just have a file that’s just a list of every item you can collect with it stats, pictures, etc, which is then easy to adjust later when the game is shipped. In your player data, you just reference the object by key.

1 Like