- Home /
Memory Game Question
Ok guys so I am struggling with this problem... So basically, I am making simple 2D game with cards that need to be matched. I'm making this using sprites & prefabs. So basically I have one script which creates card deck, and I have another script which is attached to the prefab and which chooses the random image from public list of sprites.
Prefab Code:
// front of the card
public Sprite front;
// back of the card
public Sprite back;
// List of all sprites
public List<Sprite> images;
void Start () {
// Set front to random image here...
for (int i = 0; i < images.Count; i++)
{
front = SetRandomImage(images[i]);
}
}
void OnMouseDown() {
if(!_isClicked) {
// set the image to the front
GetComponent<SpriteRenderer>().sprite = front;
// I guess I need to check here if the card is same as previous
isClicked = true;
} else {
GetComponent<SpriteRenderer>().sprite = back;
_isClicked = false;
}
}
Basically, I can't figure out the way to check if the cards match. I tried getting the sprite name of the clicked sprite but I can't check if it is the same as name of previous one. Do you have any other suggestions? Thank you.
You can create a variable to store current card,when you click on a card you assign it and when you click again you do your checks.
Answer by RobAnthem · Jan 04, 2017 at 05:08 PM
Your problem is that you did not add any actual data to differentiate the cards in your code. Short of a very unnecessary sprite iteration, it won't be able to compare one card to another. Simply create a variable to store the card type itself. For example.
Your card class might have this
public string cardName;
or
public int cardID;
then your card handler, assuming you have one, would contain
public string firstClicked;
public string secondClicked;
OnCardEvent()
{
if (firstClicked == secondClicked)
{
//we got a match
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612104009im_/https://answers.unity.com/themes/thub/images/avi.jpg)