How to better manage switching out card sprites when loading a card from a deck
In my game the player is constantly switching out cards in and out of play and I have four cards that load different stats that can be in play at a given time instead of making like 50+ prefabs is their a way to better manager switch out the sprites.
For the other variables I just have a else if statement system and that works fine but I can't load sprites the same way, the only way unity will load them is if I have a script that just handles images like this
Update if (card a = "this card name") this card.sprite = Resources.loadetc
I cant find any info on a solution because no one seems to be making a card game or etc like mine
Answer by Dibbie · Jun 14, 2016 at 07:55 AM
Well this isnt specific to just card games... Iv recently created a 2D arena/fighting game using the same idea, one prefab as a generic character, scripts to handle the stats, and a global script that handles spawning that 1 prefab, and altering the stats and sprite of that prefab, based on specific conditions in my game. You could mimic the same idea.
Create your one prefab card, kind of as a "template" with all the scripts on it, then by a seperate script - probably the one that handles allowing the player to switch between cards or some type of "global" script, create conditions that will have your script know which image to switch the Instantiated card to. Depending on how you handle your "conditions" your method may be different.
For example, you can do it by "card name", or "card id", and switch the sprite from an array, with the same index as the "card id".
Essentially, the logic you are using now (if you prefer to load everything from Resources instead of setting it in the inspector), is probably the best way to do it, you are checking if its one specific condition that will always return one "card" in your case, and setting the sprite to a specific sprite based on that.
To avoid your "like 50+" if-statements, you would reference your prefab to the script that should be updating its sprite, and in your prefab whenever this card changes, and the name of the card is updated, make sure that name is public - be it the game obects name, or a public string variable that represents the name in a script attached to the card, and instead of: if (cardA = "this card name"), it would then be: if(cardInEffect = cardA.name).
So there are a few ways you can approach it.
Your answer
Follow this Question
Related Questions
How can i save the image of the object OnApplicationQuit 0 Answers
How to set prefab images from script? 2 Answers
How I can change the sprite of the image because the code doesn't work? 1 Answer
Changing UI Image's sprite, preserve aspect ratio is checked but not working? 0 Answers
Inconsistent visibility of small sprites 0 Answers