URGENT: destroying an instantiated prefab

Hi Everyone,

This is very urgent and could be the differenc between a pass and a fail on an assignment of mine. The game I have made is a mod on the original snake game from the old nokia mobile phones. At the moment the snake is eating food and stantiationg a sphere at the end of the head each time you eat a piece of food in the game. I want it so that when you eat a different piece of food you remove the last piece of tail that has been instantiated. This is the script I am using. Thank you for any help, btw very urgent like 2 and abit hours urgent :slight_smile: `using UnityEngine;
using System.Collections;

public class SnakeMovement : MonoBehaviour
{

public Transform Rigidbody;
public Transform Rigidbody1;
private int food;
public GameObject Piece;
private GameObject lastPiece;
public AudioSource source1;

public float pSpeed = 10.0f; //Player speed
public bool pAlive = true; // Is Player alive?
public bool puActive = false;  //Is a power-up active?
public float pTimer = 5.0f; //Power-up base timer
public float speed = 100.0F;



// Use this for initialization
void Start()
{
    
    lastPiece = gameObject;
   
    
}

// Update is called once per frame
void Update()
{
    transform.Translate(new Vector3(0, 0, 0.066f));
    if (Input.GetKeyUp(KeyCode.RightArrow))
        transform.Rotate(new Vector3(0, 90, 0));
    else if (Input.GetKeyUp(KeyCode.LeftArrow))
        transform.Rotate(new Vector3(0, -90, 0));

	if (Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" ) )
	{
		source1.audio.Play();
	}
	
	else if (!Input.GetButton( "Horizontal" ) && !Input.GetButton ( "Vertical") && audio.isPlaying )
	{
		source1.audio.Stop ();
	}

	//start timer for powerup
	if (puActive)
	{
		pTimer -= Time.deltaTime;
	}
	
	//default values for player go here
	if (!puActive)
	{
		pSpeed = 10.0f;
	}
	
	//reset timer and player stats
	if (pTimer <=0)
	{
		pTimer = 10.0f;	
		puActive = false;
		pSpeed = 10.0f;
	}
    

}



void OnTriggerEnter(Collider col)
{
    if (col.gameObject.tag == "Healthy Food")
    {
        
        addPiece();
        Destroy(col.gameObject);
        
    }
	if (col.gameObject.tag == "Junk Food")
		
	{
		addPiece();
		Destroy(col.gameObject);
        
	}
}


private void addPiece()
{
    var newPiece = Instantiate(Piece, transform.position + new Vector3(20,0,20), Quaternion.identity) as GameObject;
    newPiece.name = "Piece";
    newPiece.GetComponent<SmoothFollow>().target = lastPiece.transform;
    lastPiece = newPiece;
}

}`

Use an array to store the instantiated prefabs in and simple do Destory(prefabArray[index])

You would need to store a reference to the pieces that you are spawning inside the addPiece function. A good way to do this would be to have a dynamic array, every time you add a piece, you add it to the array too, then, when you want to remove the last piece, simply remove the last array index.