How can I dynamically load the correct sprite from a sprite sheet?

Posted by Leonard Challis on Game Development See other posts from Game Development or by Leonard Challis
Published on 2014-08-24T10:05:40Z Indexed on 2014/08/24 10:31 UTC
Read the original article Hit count: 294

Filed under:
|
|
|

I am making a simple card game in unity. The game is based on a standard 52-card pack, with identical backs for unique faces. In my particular game different cards are worth different values and have various special abilities. The game will have 52 cards on the table (on the draw position or in the face-down deck or in someone's hand) at all times, so this number won't change.

I thought that making a Card prefab and instantiating 52 of these manually would be a bad idea. Even doing it in code, I thought, would be a bit OTT, and that I should just instantiate visual cards when they are face-up to the player.

I have a sprite sheet of the 52 cards and the back, which is imported as a Sprite in multiple mode, sliced in to a grid containing all the cards needed to play the game.

The problem I now face is that, through my GameController script I want to generate a shuffled pack of cards, deal some to each player and then show those cards to a player. However, I am not sure of the best way, or even if it's possible, to do this dynamically with the sprite sheets as they are. For instance if I have the following:

private CardRank rank;
private CardSuite suite;

private void Start()
{
    this.rank = CardRank.Ace;
    this.suite = CardSuite.Spades;
}

This class would be instantiated by the game manager. I would have 52 of these in code.

Whenever I have to visually show a card in the scene, I would use a card prefab, which is essentially a game object with a SpriteRenderer on it. I would need to dynamically load the correct sprite for this object from the spritesheet.

The sliced sprites from the sprite sheet actually have names in the format AS (Ace of Spades), 7H (Seven of Hearts), etc - though this was a manual thing I did myself of course.

I have also tried various alternative solutions, including creating animations, having separate sprites not in a spritesheet and having an array of available sprites in an array with a specific index for each card, but none seem as elegant as trying to load the correct sprite at runtime, as I'm trying to.

So, how do I load a specific sprite from a spritesheet at runtime? I'm open to suggestions, even those that make me think differently about how to approach the problem.

© Game Development or respective owner

Related posts about 2d

Related posts about unity