How to stop linerender when it hits an object

I’m making a FPS and am trying to give my gun a laser sight(so a laser pointer basically) and am having trouble with my script as the laser still shines trough walls and does not stop like i want it to.

function Update () {
var LaserSight : GameObject;
var hit : RaycastHit;
Physics.Raycast(transform.position, transform.forward, hit);
if (hit.collider) {
LaserSight.SetPosition(1, Vector3(0,0,hit.distance));
}
else {
LaserSight.SetPosition(1, Vector3(0,0, 5000));
}
}

I also tried this code

function Update () {
    var lineRenderer : LineRenderer = GetComponent(LineRenderer);
    lineRenderer.useWorldSpace = false;
    lineRenderer.SetVertexCount(2);
    var hit : RaycastHit;
    Physics.Raycast(transform.position,transform.forward,hit);
    if(hit.collider){
    lineRenderer.SetPosition(1,Vector3(0,0,hit.distance));
    }
    else{
        lineRenderer.SetPosition(1,Vector3(0,0,5000));
    }
}


@script RequireComponent(LineRenderer)

The endposition of the line renderer looks strange in both cases. Also: don’t forget to set the start positon of the line renderer.

Try something like this:

lineRenderer.SetPosition(0, transform.position );
if(hit.collider){
 lineRenderer.SetPosition(1, hit.point);
}
else {
 lineRenderer.SetPosition(1, transform.position + transform.forward * 100.0f );
}

(I know this conversation occurred long time ago. For people who are in search of the same question…)

Try using Physics.Linecast for our line renderer, instead of Physics.Raycast.

Also check this out, it is explained well by @tsnyder321