Reusing the same game object with different sprites

I am not sure how to approach this. I have a given gameobject called collectible.go, which always behaves the same way: when the player touches it, it disappears and adds its value to the player’s score. So this collectible.go has a collisionobject, a collectible.script and a sprite. The sprite is my concern.

This collectible can look different and have different values depending on its nature: a coin, a diamond, a gold nugget. Thing is, I can’t just add some Game Object files to the level collection and change their sprite, because… all of them change!

How can I reuse the same game object? Because creating a game object for each collectible, given they behave exactly the same, doesn’t seem too sensible…

The only solution I’ve come up with is setting the sprite and the atlas (and the score value) in the collectible.script as properties, so I can configure them in the editor, and then change their sprite in runtime - it works if I do it in runtime. But that makes level design a bit more cumbersome…

1 Like

When you say “different sprites”, do you mean the flipbook animation?

For instance, when spawning a game object from a factory, you can set the animation when spawning.
(I’m assuming they all use the same .atlas, as that will reduce the number of draw calls)

See factory.create() for the doc.

E.g. something like this:

	factory.create("#factory", vmath.vector3(200, 200, 0.3), nil, {animation = hash("triangle")})
	factory.create("#factory", vmath.vector3(300, 200, 0.3), nil, {animation = hash("circle")})

Then you can check that animation in the receving script:

go.property("animation", hash(""))

function init(self)
	if self.animation ~= hash("") then
		sprite.play_flipbook("#sprite", self.animation)
	end
end

Here is the test project:
FactoryTest.zip (414.4 KB)

3 Likes

Right, thanks @Mathias_Westerdahl, I’ll end up doing something like that and using placeholders while in edit mode.

1 Like

You don’t even have to have a script on the collectible.go:

local id1 = factory.create("#factory", vmath.vector3(200, 200, 0.3)
sprite.play_flipbook(msg.url(nil, id1, "sprite"), "triangle")

local id2 = factory.create("#factory", vmath.vector3(300, 200, 0.3)
sprite.play_flipbook(msg.url(nil, id2, "sprite"), "circle")

Although I now realise that with the go.property() you get the ability to change the value in the editor, which is probably what @playmedusa wants! So what @JCash suggests is a good solution!

2 Likes