How to make collectables trigger scene change?

Godot Version

4

Question

I want to make it so when my player collects a certain amount of apples, it completes the level and leads to the victory screen. I’m using area 2d and everything is triggered by on_body_entered. this is my apple script:

extends Area2D

func _on_body_entered(body):
	if body.is_in_group("playerreal"):
		World.has_apple = true
		self.visible = false

I would suggest you to look into how Autoload works.

You can then create a GameManager autoload that would keep track of apples collected and scene changing, e.g.:

#GameManager.gd autoload
extends Node

var apples_to_collect: int = 10 # or ideally count the apples dynamically at the start of the game
var apples_collected: int = 0

func register_apple() -> void:
	apples_collected += 1
	if apples_collected >= apples_to_collect:
		get_tree().change_scene_to_file("res://path/to/your/scene.tscn")

And change your apple script to include that new function

#apple.gd
extends Area2D

func _on_body_entered(body):
	if body.is_in_group("playerreal"):
		World.has_apple = true
		self.visible = false
		GameManager.register_apple()
1 Like

That did the trick! Thank you

1 Like