Building a Face Generator, need to destroy previous instance after pressing key a second time
I am building a Face Generator, everything works fine but my problem is that every time I press Space Bar it makes the randomized elements appear on top of one another, I need a way to destroy the previous face once the key is pressed a second time to generate a new one. I'm not sure how to proceed!! Thanks for the help!!
Code:
using UnityEngine;
using System.Collections;
public class GeneratorScript : MonoBehaviour {
public Transform spawnhats;
public Transform spawnfaces;
public Transform spawneyes;
public Transform spawnmouths;
public Transform spawnbackgrounds;
public GameObject [] eyes;
public GameObject [] hats;
public GameObject [] faces;
public GameObject [] backgrounds;
public GameObject [] mouths;
private bool faceAppeared;
// Use this for initialization
void Start () {
faces[0]=GameObject.FindGameObjectWithTag("face1");
faces[1]=GameObject.FindGameObjectWithTag("face2");
faces[2]=GameObject.FindGameObjectWithTag("face3");
faces[3]=GameObject.FindGameObjectWithTag("face4");
eyes[0]=GameObject.FindGameObjectWithTag("eyes1");
eyes[1]=GameObject.FindGameObjectWithTag("eyes2");
eyes[2]=GameObject.FindGameObjectWithTag("eyes3");
eyes[3]=GameObject.FindGameObjectWithTag("eyes4");
hats[0]=GameObject.FindGameObjectWithTag("hats1");
hats[1]=GameObject.FindGameObjectWithTag("hats2");
hats[2]=GameObject.FindGameObjectWithTag("hats3");
hats[3]=GameObject.FindGameObjectWithTag("hats4");
backgrounds[0]=GameObject.FindGameObjectWithTag("back1");
backgrounds[1]=GameObject.FindGameObjectWithTag("back2");
backgrounds[2]=GameObject.FindGameObjectWithTag("back3");
backgrounds[3]=GameObject.FindGameObjectWithTag("back4");
mouths[0]=GameObject.FindGameObjectWithTag("mouths1");
mouths[1]=GameObject.FindGameObjectWithTag("mouths2");
mouths[2]=GameObject.FindGameObjectWithTag("mouths3");
mouths[3]=GameObject.FindGameObjectWithTag("mouths4");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("space")){
faceAppeared = true;
Instantiate (faces[Random.Range(0,faces.Length)], spawnfaces.position, spawnfaces.rotation);
Instantiate (eyes[Random.Range(0,eyes.Length)], spawneyes.position, spawneyes.rotation);
Instantiate (hats[Random.Range(0,hats.Length)], spawnhats.position, spawnhats.rotation);
Instantiate (backgrounds[Random.Range(0,backgrounds.Length)], spawnbackgrounds.position, spawnbackgrounds.rotation);
Instantiate (mouths[Random.Range(0,mouths.Length)], spawnmouths.position, spawnmouths.rotation);
}
}
}
Comment