Wednesday, June 24, 2015

unity - How can I get multiple sprites on a Unity2D Sprite Renderer


I have a GameObject that I want to have multiple sprites. I tried adding an extra Sprite Renderer, but it tells me I can't add the same component multiple times.


I'd really rather not have to have four GameObjects just to display this thing correctly.


For example, I would want to have a tile background, a tile artwork, a tile character, and a nice shine on the top. If I were to make that all a single image, I would have to export nearly a thousand images to get all possible combinations.


Tile Background: Tile Background



Tile Artwork: Tile Artwork


Tile Character:Tile Character


Shine (Barely visible): Tile Shine


Everything put together how I want it in-game: Final Image



Answer



Yes, you'll need to have a single game object for each sprite, but you'll only have as many game objects as you have layers.


So you'd create a game object with the following children (and save it as a prefab): Icon game object


You can then have a script that changes the sprite for each layer:


public class Icon : MonoBehaviour
{

public SpriteRenderer artwork;

public void SetArtworkSprite(Sprite art)
{
artwork.sprite = art;
}
}

The Icon script would be in the Icon game object and would have all its fields linked with the child game objects. So then you can have an icon generator script as so:


public IconGenerator : MonoBehaviour

{
public Icon iconPrefab;

public void CreateIcon(...)
{
Icon newIcon = Instantiate(iconPrefab) as Icon;
newIcon.SetArtworkSprite(...);
newIcon.SetBackgroundSprite(...);
[...]
}

}

If you REALLY need everything to be a single game object, than I believe you can achieve this by creating a shader that takes X textures and renders them. But I'm not sure if it's worth it.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...