How to change the animation of an object depending on the number of collected items

Godot Version 4.2

I’m trying to create the end of a level that is only active when there is a certain number of collected objects. But I’m already stuck on changing the animations, I don’t really understand how to access the variable in the character’s script, which counts the number of collected fruits, and force the finish flag to change at least the animation

I have
var fruits = 0
in the character script, which changes depending on the fruit script
var Player = "res://Player/Player"

func _on_body_entered(body):
if body.name == "Player":
body.fruits += 1
queue_free()

But how can I use the resulting number in the script for the finishing flag?

I’m new to all of this so any help would be greatly appreciated

1 Like

(You should format your code here using the </> button.)

There are a few different ways to handle this, depending on how your scene is set up.

I would suggest making a sort of “game manager” script on a node which is a (grand-)parent of both the Player and the finish flag nodes.

image

I would create a signal in the Player script which is emitted when the player’s fruit count changes:

# in player script
signal fruits_changed
var fruits = 0:
	set(value):
		fruits = value
		fruits_changed.emit()

Then, I would connect that signal to a method on the game manager script that might look like this:

# game manager script
@onready var player = $Player # path of the player node
@onready var finish_flag = $FinishFlag # path of the finish flag

func _on_player_fruits_changed():
	if player.fruits >= 10:
		finish_flag.activate_finish()

image

And of course, having a script on the finish flag with a func activate_finish().

You could connect the signal directly from the player to the finish flag, and avoid having a game manager script, but I wouldn’t recommend doing that, because it makes it more difficult to reorganize your scene later if needed.

You can read about signals here: Using signals — Godot Engine (stable) documentation in English

And you can read about getter/setter functions (properties) here: GDScript reference — Godot Engine (stable) documentation in English

2 Likes

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