Unity 2D: how to destroy only one prefab clone when clicking on

so I have a problem: D. I created a simple script that will instantiate the ball at mouse coordinates when the screen is clicked. Then I went ahead and created a second script. In the second script that was attached on the ball assembly, I tested the mouse click, when it happened, I removed the GameObject ball. I assigned the ball in front of the ball to the GameObject variable. The only problem (also the reason why this is not a question that I hope ...) is when I click on the ball it removes all the balls. I know this is because they are all just one team. I thought I would solve this by giving a separate name to each prefix wedge and then removing them by name, but Im pretty shore unity has a better solution. I don't mind javascript or C # solutions, thanks!

PS: Im using Destroy method.

+3


source to share


2 answers


It looks like you are listening for a mouse click in the second script, but not checking if you want to click on the ball. Instead, you should check if the mouse is hitting the ball by throwing the beam.

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);
  }
}

      

+4


source


I ran into this problem, but in my case I have an array GameObject[]

and select some element in that array, then clone it and show it randomly ...

I run into this since I have an array GameObject

and I am thinking about how to destroy it, in particular because if I use a loop it will be destroyed sequentially ...

Well here is a tutorial on how to destroy .... video by 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 the box collider component to the game object.

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

0


source







All Articles