- Home /
The question is answered, right answer was accepted
Remove and Destroy Instantiated object in list
Hello, I'm a beginner learning how to use Unity and I'm following a tutorial (https://noobtuts.com/unity/2d-snake-game) to make a simple snake game. How do I remove a tail component and destroy it. Right now I can remove it from the tail but it will stay on the GameScene. I want to remove one tail component from the list and destroy it so that it doesn't stay on the Scence.
The one white pixel is the component that got remove from the snake. And I want to destroy that that.
void Move()
{
if (GameController.isPaused) return;
Vector2 currentPos = transform.position;
transform.Translate(direction);
if (ate)
{
var newPart = (GameObject)Instantiate(tailPrefab, currentPos, Quaternion.identity);
tail.Insert(0, newPart.transform);
length++;
ate = false;
}
else if (tail.Count != 0)
{
tail.Last().position = currentPos;
tail.Insert(0, tail.Last());
tail.RemoveAt(tail.Count - 1);
}
if (poison)
{
{
tail.RemoveAt(tail.Count - 1);
poison = false;
}
}
Answer by Legend_Bacon · Nov 29, 2019 at 09:39 PM
Hello there,
To destroy a GameObject in Unity, you can simply call Destroy (gameObjectYouWantDestroyed);
.
In your case, the end of that code up there would be
if (poison)
{
{
Destroy(tail[tail.Count-1].gameObject);
tail.RemoveAt(tail.Count - 1);
poison = false;
}
}
I hope that helps!
Cheers,
~LegendBacon