3
votes

so I have a problem :D. I created a simple script that will instantiate a prefab of a ball on mouse coords when clicked onto the screen. Then I went on and created a second script. In the second script, wich was attached on the prefab of a ball, I tested for mouse click, when that happened I deleted a GameObject ball. I assigned the ball prefab to the GameObject variable ball. The only problem is (also the reason why this is not a dulplicate question, atleast I hope..) that when I click on the ball it deletes all the balls. I know that its happening because they are all basically just one prefab. I thought Ill solve it by giving seperate name to each prefab cline and then deleting them by name, but Im pretty shore unity has a better solution. I dont mind javascript or c# solutions, thanks!

PS: Im using the Destroy method.

2

2 Answers

4
votes

Sounds like you are listening to a mouse click in your second script but not checking if you're clicking on the ball. Instead you should be checking if the mouse is hitting your ball by casting a ray.

if (Input.GetMouseButtonDown(0)) 
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if(Physics.Raycast(ray,out hit))
    {
        if(hit.collider.gameObject==gameObject) Destroy(gameObject);
    }
}

edit-> for unity2d:

if (Input.GetMouseButtonDown(0)) 
{
   RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

   if(hit.collider != null)
  {
        if(hit.collider.gameObject==gameObject) Destroy(gameObject);
  }
}
0
votes

I encountered this problem, but in my case I've got an array of GameObject[] and choose some item in that array then clone it and display it randomly...

I encounter this since I have an array of GameObject and thinking of how should I destroy it specifically, because if I use loop it will destroy sequentially...

Well there's a tutorial on how to destroy.... video from Jay AnAm

void Update(){
    if(Input.GetMouseButtonDown(0)){
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if(Physics.Raycast(ray, out hit)){

            BoxCollider bc = hit.collider as BoxCollider;
            if(bc != null){
                Destroy (bc.gameObject);
            }
        }
    }

Make sure to add component of box colliider to the gameobject.

Check this link https://www.youtube.com/watch?v=2tknfsylens