Breaking out of the right loop
im trying to only add a card to my hand if it doesnt already exist, this is the code i use:
public List<Card> playerHand = new List<Card>();
public void LoadCards ()
{
Debug.Log("Loading Cards!");
for (int i=0; i < this.transform.childCount;i++)
{
foreach (Card card in playerHand)
{
if (this.transform.GetChild(i).GetComponent<Card>() == card)
{
break;
}
}
playerHand.Add(this.transform.GetChild(i).GetComponent<Card>());
}
}
The problem is that my break just brings the loop back to the foreach, while i need it to go back to the for loop to make sure i dont add dublicate cards
Comment
Best Answer
Answer by ElDo · Nov 14, 2015 at 05:52 AM
probably Change your code to:
public List<Card> playerHand = new List<Card>();
public void LoadCards ()
{
Debug.Log("Loading Cards!");
bool bFound=false;
for (int i=0; i < this.transform.childCount;i++)
{
foreach (Card card in playerHand)
{
if (this.transform.GetChild(i).GetComponent<Card>() == card)
{
bFound=true;
break;
}
}
if(bFound)break;
playerHand.Add(this.transform.GetChild(i).GetComponent<Card>());
}
}
no. your code doesn't work as expected because you Exit the Loop after adding the Card which is what he didn't wanted to :-P
lol ok you got me, guess I wasn't paying attention enough.
Your answer
Follow this Question
Related Questions
For loop not working 1 Answer
Nested For loop Grouping 0 Answers
HOW to USE LOOPS withinh Update??? 0 Answers
Nested coroutines 0 Answers
Nested For Loop Question 1 Answer