Keep data between rooms
You want the player’s lives and coins to stay the same when it moves on to the next level.
When the game switches rooms, the instances of the old room go away. There are two ways to keep one alive.
A global object
Section titled “A global object”A global object is created once, in the first room, and exists in all the others, without you placing an instance in each level. It is the right place for a game controller.
- Create an object, for example
Controle, with the variablesmoedas(coins) andvidas(lives). - Under Projeto › Configurações do projeto… (Project › Project settings), in Objetos globais (global objects), click + Objeto global and choose
Controle.
From any other object, find the controller with instance:
onTouchStart<Player>([this](Player&) { instance<Controle>()->moedas += 1; destroy();});instance<Controle>() returns the first living instance of the object, or nullptr if there is none.
A persistent object
Section titled “A persistent object”Check Persistente (persistent) in the object’s Inspector. The instance goes to the next room with everything it had: variables, timers, position.
Use it when the instance is already in a room and needs to come along, like the player itself.
Things to watch out for
Section titled “Things to watch out for”restart()doesn’t recreate a persistent or global object. If the game starts over on game over, reset the lives and coins yourself.- The position is kept too. A persistent player arrives in the new room at the same
xandyit was at. Reposition it in the code if you need to. - Don’t keep a pointer to another instance. It can go away when the room changes. Keep a Handle:
Handle<Enemy> alvo;if (Enemy* perto = closest<Enemy>()) alvo = perto->handle<Enemy>();// later:if (Enemy* enemy = alvo.get()) enemy->destroy();See also
Section titled “See also”- Switch rooms.
- Instances:
instance<T>(),count<T>(),each<T>(fn). - Project settings.
