Making Raycast line visible

I want to make a visible line, where start point is fixed and end point can change.

I tried to make it with DrawRay. It’s all fine, but I can see the line through the wall:

void Update()
    Vector3 forward = transform.TransformDirection(Vector3.forward) * 30;
    Debug.DrawRay(transform.position, forward,;

Then I tried to use Line Renderer component, but I can’t see the line at all…


How can I solve it?

i really dont see a problem with the ray going through the wall since its a debug feature but non the less you will need to start a raycast (if you dont know what it is its a way to detect object/objects that are in a certian direction, the code will look something like this :

void Update()
            DetectHit(transform.position, 40, transform.forward);

        RaycastHit DetectHit(Vector3 startPos, float distance,Vector3 direction)
            //init ray to save the start and direction values
            Ray ray = new Ray(startPos, direction);
            //varible to hold the detection info
            RaycastHit hit;
            //the end Pos which defaults to the startPos + distance 
            Vector3 endPos = startPos + (distance * direction);
            if (Physics.Raycast(ray, out hit, distance))
                //if we detect something
                endPos = hit.point;
            // 2 is the duration the line is drawn, afterwards its deleted
            Debug.DrawLine(startPos, endPos,, 2);
            return hit;

Thanks to, @Moaid_T4’s script I was able to quickly whip up a laser script. It uses LineRenderer and the laser won’t go through walls. Attach LaserScript.cs and LineRenderer to the player’s game object.

Here is LaserScript.cs:

using UnityEngine;
using System.Collections;

public class LaserScript : MonoBehaviour
	public LineRenderer laserLineRenderer;
	public float laserWidth = 0.1f;
	public float laserMaxLength = 5f;

	void Start() {
		Vector3[] initLaserPositions = new Vector3[ 2 ] {, };
		laserLineRenderer.SetPositions( initLaserPositions );
		laserLineRenderer.SetWidth( laserWidth, laserWidth );

	void Update() 
		if( Input.GetKeyDown( KeyCode.Space ) ) {
			ShootLaserFromTargetPosition( transform.position, Vector3.forward, laserMaxLength );
			laserLineRenderer.enabled = true;
		else {
			laserLineRenderer.enabled = false;

	void ShootLaserFromTargetPosition( Vector3 targetPosition, Vector3 direction, float length )
		Ray ray = new Ray( targetPosition, direction );
		RaycastHit raycastHit;
		Vector3 endPosition = targetPosition + ( length * direction );

		if( Physics.Raycast( ray, out raycastHit, length ) ) {
			endPosition = raycastHit.point;

		laserLineRenderer.SetPosition( 0, targetPosition );
		laserLineRenderer.SetPosition( 1, endPosition );

I hope this script helps, @dmitry.kozyr