Destroy(this.gameObject) destroys all the obejcts in the scene, i want only the one that is clicked on
I want to destroy gameobject when they are clicked on, but right now when i click on one all the gameobjects in the scene destorys, how do i fix this?
void Update ()
{
ClickedOnAction();
}
void ClickedOnAction()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Destroy(gameObject);
}
}
This is the code i have right now. And if it has any difference, i have many of the same objects in the scene so how do i fix this?
Answer by ScaniX · Sep 12, 2016 at 11:47 AM
Your code contains no condition other than mouse pressed, so every gameObject containing this script will of course be destroyed.
If your object has a collider, you can use the event method OnMouseDown()
or OnMouseUpAsButton()
(more similar to a click on that object) and add the line Destroy(gameObject)
there.
This is the whole script for this:
void OnMouseUpAsButton()
{
Destroy(gameObject);
}
Make sure to give your object a collider (assuming it is a 3D object). Also see here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseUpAsButton.html
Cant realy get it to work, can you be a bit more specific on how to fix it?
Add a collider if your objects do not have one.
Replace everything you have with the following:
void On$$anonymous$$ouseDown() { Destroy(gameObject); }
No need for updates and checking and all of the other stuff; On$$anonymous$$ouseDown()
checks whether the cursor is over the object (even if the cursor is hidden and sitting at the centre of the screen) and then destroys it if so.
I kinda know what you are talking about but now when i run the function the objects dosent even come on to the sceen, they gets destroyed even before they enter beacuse i have On$$anonymous$$ouseDown in update. void Update () {
On$$anonymous$$ouseDown();
}
void On$$anonymous$$ouseDown()
{
Destroy(gameObject);
}