Touch activates all in scene, expecting just the one i touched

this should be pretty easy for you guys!

i have two cubes with this script on them.
the touched cube and the untouched one both run the script as if both are touched.

var particle : GameObject;

function Update () {
	for (var touch : Touch in Input.touches) {
		if (touch.phase == TouchPhase.Began) {
			// Construct a ray from the current touch coordinates
			var ray = Camera.main.ScreenPointToRay (touch.position);
			if (Physics.Raycast (ray)) {
				// Create a particle if hit
				Instantiate (particle, transform.position, transform.rotation);
				
			}
		}
	}
}

The code in the body of the “if” statementt:-

if (Physics.Raycast (ray)) {
  ...			
}

will be executed when the ray hits anything, so whenever there is a collider at the touched point then both objects will execute this code. If you want to tell for each object whether it was the one that was touched, you need to use something like this:-

var hit: RaycastHit;

if (Physics.Raycast (ray, hit)  hit.transform == this.transform) {
  ...			
}

thanks!

i added the variable “hit” in front of the if to get it to work.

var hit : RaycastHit;
			if (Physics.Raycast (ray, hit)  hit.transform == this.transform)
			{
				// Create a particle if hit
				Instantiate (particle, transform.position, transform.rotation);
				
			}