Instantiating GameObjects from a List
I am trying to draw cards from a List 2 at a time in order. Then moving those cards to another list so they are not drawn again on the next click. I almost have it working but the order seems to be off. It is always off in the same order. The lists are populating correctly but in the wrong order [always consistent but still]. *[I do have an error when I draw twice that exception is out of range - I understand I need to do something about this as well, but that is my next task].
I am confused to why the order seems to be off... * Any help is appreciated, I have been doing tons of reading on lists and its getting better bit by bit.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawCardsNoRepeat : MonoBehaviour
{
public GameObject Card1;
public GameObject Card2;
public GameObject Card3;
public GameObject Card4;
public GameObject Card5;
public GameObject Card6;
public GameObject PlayerArea;
public List<GameObject> Deck = new List<GameObject>();
public List<GameObject> PlayerHand = new List<GameObject>();
void Start()
{
Deck.Add(Card1);
Deck.Add(Card2);
Deck.Add(Card3);
Deck.Add(Card4);
Deck.Add(Card5);
Deck.Add(Card6);
}
public void OnClick()
{
for (var i = 0; i < 2; i++)
{
GameObject playerCard = Instantiate(Deck[i], new Vector3(0, 0, 0), Quaternion.identity);
playerCard.transform.SetParent(PlayerArea.transform, false);
Deck.Remove(Deck[i]); //tried putting playerCard in here but it doesn't seem to work...
PlayerHand.Add(playerCard); //it works here though...
}
}
}
Answer by Hellium · Dec 18, 2021 at 10:09 PM
With your current code, you are instantiating and removing the first remaining card of the list, then, the third one of the list. Because you're removing the first one (index 0), Deck[1]
is the third element of the "original" list (since all the cards have been shifted to the left when you removed Deck[0]
.
for (var i = 0; i < 2 && Deck.Length > 0; i++)
{
GameObject playerCard = Instantiate(Deck[0], new Vector3(0, 0, 0), Quaternion.identity);
playerCard.transform.SetParent(PlayerArea.transform, false);
Deck.RemoveAt(0);
PlayerHand.Add(playerCard);
}
Note: instead of a List<GameObject>
, Deck
could be a Queue<GameObject>
.
WOW @Hellium thank you so much for such a quick response! It worked, except instead of Deck.Length I used Deck.Count. I really appreciate it, I have lots more studying to do. I will ponder over your response so I can fully comprehend it, I think I need more studying on Lists functions, and that for (var i = 0; i < 2 .....) stuff