How to add a Gameobject to a list and remove it from Game World?
I want to add cards (that are already instantiated) to my discard pile list, but then also remove them from the Game World so that they only exist as part of the list. I've tried:
discard.Add(card);
DestroyImmediate(card);
and it doesn't work, it adds the card to the list and then destroys the object, so the list is empty. How would I go about doing this
Answer by gribbly · Jun 12, 2016 at 06:02 PM
What are you trying to achieve? What does the discard pile list do?
Would it solve your problem to add a copy of the card to the discard list?
GameObject cardCopy = card;
discard.Add(cardCopy);
DestroyImmediate(card);
What im trying to accomplish is to add gameobjects to a list, yet not have them actually exist in the world until I instantiate them. Once I've instantiated them, I want to move them to another list and remove them from the game world so they exist solely in the list and not in the hierarchy. I already tried making a copy, and it doesn't seem to work. I still get the exact same result which is when i destroy the card, I get an empty spot in my discard list and it still is in the game world. If it changes anything, the card variable is static.
the discard pile list serves as a discard pile basically, I have to have one for this particular game (can't just reshuffle the deck) because cards will be added to and taken away from the deck. So i need to keep track of what cards still exist but have been played
Well ins$$anonymous$$d of Instantiating and destroying your objects you ought to look in to object pooling. There's a tutorial on this website for that, but the basic premise is that you call yourGameObject.setActive(false);
whenever you want it deactivated (disappear, not visible/functioning for the time being), and yourGameObject.setActive(true)
when you want it visible.
The combination of Instantiate() and any Destroy() method is extremely inefficient to be doing every game loop or even most of the time. It will kill your frame rate. Object pooling is the way to go, and its actually more manageable. You won't have to check for null references all the time because whatever you need will already exist.
Also when you call setActive() on anything, the thing still exists. It doesn't disappear from memory, but it does disappear from the game environment (from the players perspective). Using this and object pooling you could keep your List of gameobjects and still have them disappear from the game.
Additionally; you can create functions like so:
public void OnEnable() { //Do stuff when enabled } //AND public void OnDisable() { //Do stuff when DISabled }
Which are called by the unity engine whenever the game object is enabled or disabled, respectively. Its really nifty.
Thanks, I'm gonna try and implement this tomorrow, put your comment as an answer and I will mark it correct ;)