- Home /
2D Sprite Trouble
Hey all, I'm making a simple playing card game and have been trying to fix this issue for the last 2 hours without success. It's kinda hard to fully show the problem but Ill try my best.
I spawn multiple card prefabs.
I create a variable name RandomCard and generate a random number between 0 and the count of my CardsInDeck list - 1.
I create a variable named DrawnCard
and assign it CardsInDeck[RandomCard]I then cycle through an array of
sprites (the card faces) and check if sprite name is == DrawnCard If so I
assign that sprite to the card.Lastly, I remove
CardsInDeck(DrawnCard).
However, the issue I'm having is that there are still double ups. All of the DrawnCard values are unique and there are no dupes. The array of sprites are all unique in name and appearance.
I hope this is clear enough to understand, if not please ask. Code Below:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class boardManager1 : MonoBehaviour {
//Deck Makeup
private List<string> CardsInDeck = new List<string>();
private List<string> cardSuits = new List<string>() {
"Clubs",
"Spades",
"Hearts",
"Diamonds"
};
//Card Creation
public Sprite[] cardImages;
public GameObject Card;
private int[] EmptyCardPositions = { -5, -3, -1, 1, 3, 5, 7 };
void CreateDeck()
{
for (int cardsInDeck = 0; cardsInDeck <= 13; cardsInDeck++)
{
for (int cardsInSuit = 0; cardsInSuit < 4; cardsInSuit++)
{
CardsInDeck.Add(cardsInDeck.ToString() + cardSuits[cardsInSuit]);
}
}
}
void DrawCard(int xPos, int yPos)
{
Instantiate(Card, new Vector3(xPos, yPos, -1), Quaternion.identity);
int randomCard = Random.Range(0, CardsInDeck.Count-1);
string DrawnCard = CardsInDeck[randomCard];
Debug.Log(DrawnCard);
foreach (var sprite in cardImages)
{
if (sprite.name == DrawnCard)
{
Card.GetComponent<SpriteRenderer>().sprite = sprite;
}
}
//Remove Drawn card from the deck
CardsInDeck.Remove(DrawnCard);
}
void Start()
{
CreateDeck();
//Create Player Hand
foreach (var position in EmptyCardPositions)
{
DrawCard(position,-4);
}
//Create AI Hand
foreach (var position in EmptyCardPositions)
{
DrawCard(position, 2);
}
}
}
Answer by scb · Dec 23, 2016 at 04:30 PM
Have you tried using the debugger, and tracing your functions step by step, all the way through? You should be able to keep an eye on the CardsInDeck list, and watch its' size and contents.
If you put a breakpoint on [line 44]
CardsInDeck.Remove(DrawnCard);
and watch the contents of your list, is it behaving?
Sorry, i know this is not technically an answer. Just an approach.
Answer by destructivArts · Dec 22, 2016 at 08:03 PM
I don't know why your code isn't working but you could just do:
CardsInDeck.RemoveAt (randomCard);
which is a less expensive remove function anyways.
Hope this helps!