How do i make an item stay gone after scene is reloaded

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By stella3321

Hi, so I am working on a 2d Platformer, and the player in game goes around picking up items. when the player falls out of bounds the scene is reset, with this code on the player:

func _on_fallout_body_entered(body):
	get_tree().change_scene_to_file("res://main-screen.tscn")

The issue is that when this happens the items that have already been picked up now reappear, and I don’t want them to.

extends Area2D

func _on_Item_body_entered(body):
	queue_free()

This is the code I currently have on the Item, so if the player doesn’t fall out of bounds the item disappears, but like I said if the scene reloads the item is back.
I already made an Autoload global script, I just don’t know what to write in it to make what I want to happen, happen.

Thank You

:bust_in_silhouette: Reply From: crossbito

To solve that problem, you can create global variables with two arrays: one for items that haven’t been obtained and the other for items that have been obtained.

# Global.gd

var items = []
var collectedItems = []

When the item starts, you can do something like this:

func _ready():
	if Global.collectedItems.has(global_position):
		queue_free() #free the item becouse already has been collected
	else:
		Global.items.append(global_position)

And when the item is deleted, you need to move the item from the items array to the collectedItems array:

func _on_Item_body_entered(body):
    Global.collectedItems.append(global_position)
    Global.items.erase(global_position)
    queue_free()

In this case, I chose to save the global position as the value because the items don’t move and they don’t share a location with other items. You could use something else, such as the name or assign a unique ID to each item. The key is to use something that won’t change when you reload the scene.

This is an idea: you could even use only one array to track what you have collected, but with two arrays, you can also track how many items the player is missing.

I hope this helps!

thank you! it worked

stella3321 | 2023-06-03 12:17