Reputation: 33
I am doing a snake-like game and when I eat an enemy I create a new clone of a prefab. Instead of creating just one clone after the main prefab, after I eat the first enemy and I have the prefab and one clone, when I eat the second enemy the game creates a clone of the prefab AND a clone of the clone.
I really don't understand why that happens, it's a short code and I can't find any mistakes. The only idea I have is that maybe this script works for every clone instead of just the player, as it should.
private void createNewPiece()
{
if(playerPieces.Count!=0)///which is the number of clones, not counting the player
clone = Instantiate(player, playerPieces[playerPieces.Count-1].transform.position, Quaternion.identity);
else
clone = Instantiate(player, lastPlayerPosition, Quaternion.identity);
playerPieces.Add(clone);
addedNewPiece = true;
}
private void movePlayerPieces()
{
if (addedNewPiece == false)
{
for (int i = playerPieces.Count - 1; i >= 1; i -= 1)
{
if (playerPieces[i] != null)
playerPieces[i].transform.position = playerPieces[i - 1].transform.position;
else Debug.Log("uhmm" + i);
}
if (playerPieces.Count >= 1 && playerPieces[0] != null)
playerPieces[0].transform.position = lastPlayerPosition;
}
else
{
for (int i = playerPieces.Count - 2; i >= 1; i -= 1)
{
if (playerPieces[i] != null)
playerPieces[i].transform.position = playerPieces[i - 1].transform.position;
else Debug.Log("uhmm" + i);
}
if (playerPieces.Count >= 2 && playerPieces[0] != null)
playerPieces[0].transform.position = lastPlayerPosition;
}
}
The more enemies I eat, the more clones the next enemy eaten creates, instead of creating just one every time.
Upvotes: 1
Views: 62
Reputation: 10320
Your snake is made of clones of the player prefab, so every part has this script. This means that the new tail-segment will also spawn another clone, alongside the head.
Try making a PlayerHead GameObject with this script and a PlayerBody GameObject without this script for the clones.
Upvotes: 1