Destroy(gameObject) destroying all instances of object

function Update ()
for (var i = 0; i < Input.touchCount; ++i)
if (Input.GetTouch(i).phase == TouchPhase.Began)
// Construct a ray from the current touch coordinates
var ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);

			if (Physics.Raycast (ray)) 
				// Destroy the game object

This is my code here, I have four separate players in my scene with this script attached to each of them.

The problem is when I run the game and I touch on one of my players, they all disappear. I just want the one I touch on to disappear. Can anyone tell me what I’m doing wrong?

This is everything in my project so far, the players are just made up of cubes and spheres as you can see


You’re not checking if the object is actually clicked. Even if you click on no player at all, but at any collider, this would cause all players to be destroyed. Look at this:

var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     var hit : RaycastHit;
          if(hit.collider== this.collider) {

When I want to do this I have to use a loop and iterate through all instances. I’d be curious if there is some way to do it in one step. Could be quite useful. :slight_smile:

What is actually happening is your script is destroying the attached gameObject when the screen is touched (line 5) and a ray drawn from the touch hits anything (line10). Test this yourself by touching the ground )or some other gameObject with a collider) and you will see the same effect.

To solve you can:

  • Use rayCastHit to check if the collider hit is on the appropriate gameObject. This is an expensive option as it still requires multiple raycasts each time you touch the screen.
  • Create one instance of this script. Use it to do the raycast and use rayCastHit to determine which object to destroy. This is more efficient and can be expanded to control all your input using SendMessage.