- Home /
Linking strings and integers?
Okay so I have a bit of an issue. I currently have this, but it's not what I want. Current system is that you draw the card, read what it says, then manually add or remove points using buttons (irrelevant so not included in my code here). I want it automatic, so basically what I want to happen is when you click a card it displays the text, then it needs to give points directly related to what was declared in the string. If the string element that's called says to add 6 points, it should then automatically add 6 points. I don't know how to do this with strings, arrays, dictionaries, or lists. Obviously I can't declare an integer or float as to what pointamount in the string, so somehow I think I need a seperate string or integers that would get called at the same time as the string, but would be linked and be specific to that string element. Someone please help me. Here's my current code:
public class Game : MonoBehaviour
{
public int PointCount;
public Text PointText;
public GameObject CardDisplayBox;
public TMP_Text CardText;
public GameObject CardButton;
public float pointCount;
#region Cards List
string[] cards = { "RANDOM CARD 1. +3 Points", "RANDOM CARD 2. +2 points", "RANDOM CARD 3. +6 points " };
#endregion
#region Card Display
public void OnCardClick()
{
CardDisplayBox.SetActive(true);
SetCard();
}
private void SetCard()
{
string randomCard = cards[Random.Range(0, cards.Length)];
CardText.text = randomCard;
}
#endregion
Answer by Namey5 · Jun 27, 2021 at 06:17 AM
This is where object-oriented programming comes in - you can create a 'Card' object that contains both the display text and points to add, then select from a list of cards rather than strings;
[System.Serializable]
public struct Card
{
string text;
int points;
public Card (string a_Text, int a_Points)
{
text = a_Text;
points = a_Points;
}
}
...
Card[] cards =
{
new Card ("RANDOM CARD 1. +3 Points", 3),
new Card ("RANDOM CARD 2. +2 Points", 2),
new Card ("RANDOM CARD 3. +6 Points", 6)
};
private void SetCard ()
{
Card randomCard = cards[Random.Range (0, cards.Length)];
// Then, just access the members of the card
CardText.text = randomCard.text;
AddPoints (randomCard.points);
}
Your answer
Follow this Question
Related Questions
Unity equivalent of GeekGameBoard? 3 Answers
How to get object to follow a curved path to reach a moving destination? 1 Answer
2D Tilebased game with blocks. Only allow to place in corners. 0 Answers
VR games using cardboard 0.7 are not showing in playstore on devices which donot have gyro sensor.. 0 Answers
How to draw border around uneven board like shown in the picture. 0 Answers