block a raycast from passing through objects

I have build a scene with multiple objects which change materials when clicked on them. Please download the sample scene I have made.

http://www.mediafire.com/download/6tfz4yc7fldyo2m/3DroomTest.exe

the problem is, the raycast goes through objects and affects objects behind them.

here is the script I use

    var hit : RaycastHit;
    var matArray : Material[];
    private var index : int;
     
    function Update () {
     
    if (Input.GetMouseButtonDown(0) && collider.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), hit, Mathf.Infinity)) {
    index++;
    index = index % matArray.Length;
    renderer.material = matArray[index];
    }
    }

That’s because you’re using collider.Raycast, which ignores other colliders, and the script is attached to the clickable objects: you click on an object, but the script running in another object behind him also “thinks” to have been clicked. A simple solution is to use OnMouseDown instead:

var matArray : Material[];
private var index : int;

function OnMouseDown(){
    index++;
    index = index % matArray.Length;
    renderer.material = matArray[index];
}

NOTE: This code requires mouse, thus it won’t work in touch-only devices. A more general case must use Physics.Raycast and make sure that only the object clicked increments the material:

var matArray : Material[];
private var index : int;

function Update(){
    var hit : RaycastHit;
    if (Input.GetMouseButtonDown(0)
      && Physics.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), hit)
      && collider == hit.collider){ // only this object responds to the click
        index++;
        index = index % matArray.Length;
        renderer.material = matArray[index];
    }
}

Use Physics.Raycast not Collider.Raycast

Collider Raycast →

Description

Casts a Ray that ignores all Colliders
except this one.

Physics.Raycast will stop at the first collider it hits.

Thank you all, will test this and update! Works perfect!! I used the Physics.Raycast variant … Thank you