Destroy GameObject in list then instantiate GameObject not working
Hi guys,
I have a script which adds players to the game but once you decide you want less players then what you have chosen, the instantiated players can't be instantiated again.
It sounds a bit confusing but bare with me, Here is the script to try and help out a bit.
public class players
{
public int playerNum;
public players (int num)
{
playerNum = num;
}
}
public int playersPlaying = 1;
List<Transform> myList = new List<Transform> ();
int addPlayers = 0;
bool gameStart = false;
public players newPlayers = new players (1);
public GameObject playerGameObject;
void Update ()
{
if (playersPlaying > 0 && !gameStart)
{
if (newPlayers.playerNum != playersPlaying)
{
newPlayers = new players (playersPlaying);
}
}
//Debug.Log (newPlayers.playerNum);
if (gameStart)
{
CreatePlayers ();
}
}
void CreatePlayers ()
{
if (gameStart)
{
if (addPlayers < playersPlaying)
{
GameObject go = Instantiate (playerGameObject);
addPlayers++;
go.name = "Player " + (addPlayers);
go.tag = addPlayers.ToString();
myList.Add (go.transform);
}
if (addPlayers > playersPlaying)
{
for (int i = 0; i < myList.Count; i++){
if(int.Parse(myList[i].tag) > playersPlaying) {
Destroy (myList[i].gameObject);
myList.RemoveAt(i);
}
}
}
}
}
public void playersUp ()
{
if (!gameStart)
{
if (playersPlaying != 4)
{
playersPlaying++;
}
}
}
public void playerDown ()
{
if (!gameStart)
{
if (playersPlaying != 1)
{
playersPlaying--;
}
}
}
public void gameBegin ()
{
gameStart = !gameStart;
}
So what I am after is that once the playerGameobject is destroyed then it can later be instantiated again.
Kind Regards,
IHackedDeath.
Hi DiegoSLTS,
O$$anonymous$$G!!!!!!!
Thank you soooo much.
I was going crazy over that as well for ages.
I can't believe it was that simple.
Haha thank you so much again :)
If you want to post that again as an answer or just specifically what the problem was I am happy to vote it as answer :)
@IHackedDeath, I converted my comment to an answer. Glad it helped.
Answer by DiegoSLTS · Sep 08, 2015 at 05:49 PM
I'm not sure I follow, you're incrementing addPlayers at some point but never decrementing it, is that OK? That's the only thing that could prevent playerGameobject to be instantiated since it'll make the Instantiate line unreachable in the future.