Godot Version
4.2
Question
I’m currently programming a [Battleship (game) - Wikipedia]
In my game I’m having a class Ship. There is also a Player class that contains an array of Ship. In one scene (“add_ships.tscn”) the player is adding the ships to the grid. Everything is stored in an autoload called Globals.
In “add_ships.gd” it looks like this:
print("Current Player: ", Globals.current_player.p_name)
Globals.current_player.p_ships.append(carrier)
... # repeat for all ships
print(Globals.current_player.p_ships)
for i in Globals.current_player.p_ships:
print("Player Ship: ", i.ship_type)
So, this works all as expected and the for-loop at the end prints correctly all ship types. But after the array p_ships has been created I’m switching the scene to the actual game scene. Here I’m having also a grid and want to add all the ships stored previously in a function that is called by _ready():
func build_players_grid():
if Globals.current_player != null:
print(Globals.current_player.p_name)
if Globals.current_player.p_ships.size() > 0:
for i in Globals.current_player.p_ships:
print("Player Ship: ", i.ship_type) # ERROR: Invalid get index 'ship_type' (on base: 'previously freed')
Globals.current_player.p_name is “Player 1”, so not null. The array has got the correct size, so it is > 0 (I’m having 10 ships total). But when the game crashes, I see in debug mode, that all 10 items of Globals.current_player.p_ships are actually null, although the same code worked in the other scene. I want to store exact copies of the ships, including position, rotation, type and so on.
How can I make the objects live from one scene to the other (I guess that “previously freed” means that the objects have been deleted in memory while the scene has changed). How can I prevent this?
Thanks a lot for helping me out!