Load tilesource in script help

I’m trying to load player skin tilesources. They are named like player_SKINNAME.tilesource and global module has the currently selected skin name.

local atlas_path = string.format("/assets/images/player/player_%s.tilesource", global.skin)
go.property("player_atlas", resource.atlas(atlas_path))

init

function init(self)
	go.set("#sprite", "image", self.player_atlas)
end

Error is about property being nil

This will not work. What you provide to resource.atlas() has to be a string. Not a variable holding a string. The go.property values are parsed at build time to ensure the correct resources are included in the project build.

If you have multiple tilesources you need to include all of them:

go.property("player_atlas1", resource.atlas("/assets/images/player/player_1.tilesource"))
go.property("player_atlas2", resource.atlas("/assets/images/player/player_2.tilesource"))
go.property("player_atlas3", resource.atlas("/assets/images/player/player_3.tilesource"))

function init(self)
	local atlas_path = string.format("/assets/images/player/player_%s.tilesource", global.skin)
	go.set("#sprite", "image", atlas_path)
end

I’m not sure if resource.atlas() accepts a .tilesource file or only .atlas file. You’ll have to try this.

There’s over 50 skins, what would be the most optimal way of selecting them based on global.skin

Ah, ok, well, you don’t want 50 go.property(resource.atlas()) because that would mean that all 50 would be loaded. This will be solved once we have implemented this: https://github.com/defold/defold/issues/6195

Until that happens your best bet is:

  1. Create 50 game objects, each with a script referencing one atlas using a go.property(resource.atlas())
  2. Create 50 factory components, referencing one game object each
  3. Check the Load Dynamically checkbox on the factory component
  4. Load the factory containing the atlas you need using factory.load()
  5. Spawn one instance of the game object
  6. Use go.get() to read the go.property
  7. Set it on the sprite

A bit complicated unfortunately. But that is the best we can do for now.

3 Likes

Here is an example from my game:
Skins loader (manager):


Skin:

4 Likes