Level switch (change level)

Yes this method works fine for me too. I also use the script to handle load and unload of each (logical) scene/level.

Name your GO as ‘loader’ and name its script as ‘script’.

in the script

local function load_title(self)
	msg.post("#title", "load")
end

local function unload_title(self)
	msg.post("#title", "unload")
end

local function load_battle(self)
	msg.post("#battle", "load")
end

local function unload_battle(self)
	msg.post("#battle", "unload")
end

function init(self)
	msg.post(".", "acquire_input_focus")
	load_title(self)
end

function final(self)
	msg.post(".", "release_input_focus")
end

function on_message(self, message_id, message, sender)
    if message_id == hash("start_game") then
    	unload_title(self)
    	load_battle(self)
    elseif message_id == hash("back_to_title") then
    	unload_battle(self)
    	load_title(self)
    elseif message_id == hash("proxy_loaded") then
    	msg.post(sender, "enable")
    end 
end

Then from your other scripts in each scene/level:

msg.post("main:/loader#script", "start_game")

msg.post("main:/loader#script", "back_to_title")

For the shared data you can simple use lua table to stored your data. Make it a lua module and then you can require it everywhere from your program. But I’m not sure this is a recommend way in Defold or not.

shared_data.lua

local M = {
  player = {
    gold = 0,
    silver = 0
  }
}
return M

any script files:

local shared_data = require('shared_data.lua')
print(shared_data.player.gold)
shared_data.player.gold = 50

And there is a restrict that game objects in one scene/level (in one collection proxies) cannot post message to other game objects in other scene/level (in other collection proxies) in the case that you’ve loaded multiple collection proxies at the same time.

6 Likes