Destroy and instantiate the game objects using keyboard event

Hi, I am new to this forum and i am new into unity3D also. I have a simple task wherein i need to instantiate gameobjects when i press "W" key and destroy the same gameObjects when i press "f" key. Till here everything is working fine. But after i destroy the gameobjects , if i press again "F" key the gameobjects doesn appear again. I don wan to use prefab. Could Anyone Help me please please.,.,., Urgent`enter code here

`using UnityEngine; using System.Collections;

public class keyboard : MonoBehaviour { public GameObject newObject; public GameObject new1;

void Update()
{

    if (Input.GetKeyDown(KeyCode.F)) 
    {

         int i;
        for( i=0;i<4;i++)
     GameObject.Instantiate (newObject, new Vector3(i * 5.0F, 9, 3), Quaternion.identity);

    }
    else
    {
        if (Input.GetKeyDown(KeyCode.W))
    {

            Destroy(this.gameObject);

            newSphere();

    }
    }
    }

void newSphere()
    {
            int x;
        for(x=0;x<4;x++)
            GameObject.Instantiate(new1,new Vector3(x * 5.0F, 9, 3), Quaternion.identity);
    }

}

1 Answer

1

Destroy(this.gameObject); will destroy this game object (script and all, including the script that's running). Probably better to save off the game objects you instantiated in the F-KeyDown phase, and destroy each of those on the W key down phase.

Something like:

var newObjs : Array;

function Start()
{
  newObjs = new Array();
}

function Update()
.. blah blah..
     // create 'em
     int i;
     for( i=0;i<4;i++)
       newObjs _= GameObject.Instantiate (newObject, new Vector3(i * 5.0F, 9, 3), Quaternion.identity);_
*.. blah blah ..*
 *// destroy 'em*
 *for( i=0;i<4;i++)*
 _Destroy (newObjs*);*_ 
_*```*_

Thanks for the reply.,.,!!! i am new to this unity3D.,.,!! can you please tell me how to save the instantiated objects?? using array??? Using array i tried but didn work ,.,., can you please tell me.,., waiting for your reply.,.,

–

Edited my answer to include some code clips

–