Loading a new sprite into an image array
Hi,
I'm trying to produce a basic BlackJack card game. I have a Resources folder containing a border image, a card back image, and a spliced image of 52 cards named cards_0...cards_52.
I have a single gameobject called GameSystem with a single C# script attached to control the entire game.
I have these two lines to use the Inspectors drag n drop method to associate the card image display in the canvas with the GameSystem.cs script:
public Image[] playerCards = new Image[5];
public Image[] dealerCards = new Image[5];
I have a new class to hold the properties for each card:
public class PlayingCard {
public string card;
public bool used;
public int value;
//Constructor for PlayingCard object
public PlayingCard (string cardSprite, int faceValue) {
card = cardSprite;
used = false;
value = faceValue;
}
}
of which I've made an array of card objects:
private PlayingCard[] deck = new PlayingCard[52];
The cards are initiated with the name of the appropriate card sprite held in the PlayingCard object card string (card_0...card_52):
string cardSprite = "cards_" + cardNumber.ToString ();
deck[cardNumber] = new PlayingCard (cardSprite, Mathf.Clamp (card + 1, 1, 10));
So, later on, in the actual game, I'm randomly chosing which card to display
int[] chosenCard = new int[4];
//deal four cards
for (int deal = 0; deal < 4; deal = deal + 1) {
bool validCard = false;
//repeat until valid card is chosen
while (validCard == false) {
int randomCard = Random.Range (1, 52)
//check if card is valid
if (deck[randomCard].used == false) {
chosenCard[deal] = randomCard;
deck[randomCard].used = true;
validCard = true;
}
}
}
Once the cards have been chosen, I'm trying to update the sprite image in the canvas with the sprite image of the chosen cards with the following code:
dealerCards[0].sprite = Resources.Load (deck[chosenCard[0]].card) as Sprite;
dealerCards[1].sprite = Resources.Load ("CardBack") as Sprite;
playerCards[0].sprite = Resources.Load (deck[chosenCard[2]].card) as Sprite;
playerCards[1].sprite = Resources.Load (deck[chosenCard[3]].card) as Sprite;
However, the images don't change, the remain with the empty image place holders.
Can someone point me in the direction of where I'm going wrong?
playerCards[n] is an image and is associated in the inspector with the correct canvas image placeholder object. playerCards[n].sprite should change the sprite image associated with that canvas image object. Resources.Load should load the named sprite from the resources folder. deck[chosenCard[n].card] is returning the correct sprite name string, eg cards_13. and it told to load "as Sprite".
Why is this not working?
Thanks in advance for any pointers.