How do I destroy an instantiated object with a mouse click?
I am simply trying to run Destroy()
on a single, clicked instantiated prefab object.
When attempting the same technique on a standard quad in the game scene (not from prefab), the GameObject is destroyed without issue.
My two attempts both failed with different results:
Using OnMouseDown
(attached to the Brick
prefab) doesn't do anything:
public class Breaker : MonoBehaviour {
void OnMouseDown () {
Destroy (gameObject);
}
}
Also tried using Update
to listen for click, but all instances of Brick
are destroyed at the same time.
void Update () {
if (Input.GetButton("Fire1")){
Destroy (gameObject);
}
}
Could you show me how you got this working? I added a box collider 2d to my prefab but when i clicked it when it spawns nothing happens or something does and all them get destroyed at once...
Answer by TBruce · Nov 16, 2016 at 08:07 PM
I do not know why the Input.GetButton("Fire1")
way is not working for you (unless Fire1
is not set to the left mouse button).
But the OnMouseDown()
method is the way to go, you only need to make sure that there is a collider on the Brick
prefab.
Your answer
![](https://koobas.hobune.stream/wayback/20220612100819im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Destroy instantiated Projectile after time 1 Answer
Using foreach to remove and delete bullet in List - C# 3 Answers
Press an image and destroy it 0 Answers
How To Generate Platforms Down Each other in a pattern with some different positions Unity 1 Answer
Destroy prefabs after they have been instantiated (C#) 1 Answer