- Home /
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); }
}
Answer by DaveA · Mar 30, 2011 at 06:52 AM
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[i] = GameObject.Instantiate (newObject, new Vector3(i * 5.0F, 9, 3), Quaternion.identity);
.. blah blah ..
// destroy 'em
for( i=0;i<4;i++)
Destroy (newObjs[i]);
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.,.,
Your answer
![](https://koobas.hobune.stream/wayback/20220613115659im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Pooling object performs the same or worse than instantiate/destroy? 1 Answer
Destroying Instantiated Obect Problem 1 Answer
Objects will not destroy after they have been instantiated 1 Answer
How to destroy instantiated object 1 Answer
I need to Instantiate a prefab at the same location where a different object was destroyed., 1 Answer