Hi, 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 one 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.
That’s most likely because all the balls have the script attached to it, that deletes the game object whenever a click occurs.
To make sure you only delete the ball you clicked on, you need to use some more tricks, mainly this one:
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
print("Destroyed ball at " + Input.mousePosition);
}
}
Create a separate method with that (that is NOT on every ball), and use the snippet of code in its Update
method. That should work fine if the only objects in your scene are the balls you want to delete when clicked on.
Well if your are using unity 2D, then it would be definitely work for your, and make sure you have attach 2d physics collide with your prefab.
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);
}
}