# How can I draw a linerenderer line between two vector3 positions using the mouse left button click?

This code is drawing a line but it's not drawing it on the camera in front of the camera.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class DemoScriptDraw : MonoBehaviour
{
private List<Vector3> _positions = new List<Vector3>();
private LineRenderer lr;

private void Start()
{
lr = this.GetComponent<LineRenderer>();
}

private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 pos = Input.mousePosition;
pos = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z));

if (_positions.Count == 2)
{
SpawnLineGenerator(_positions[0], _positions[1], Color.red);
}
}
}

void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
{
GameObject myLine = new GameObject();

LineRenderer lr = myLine.GetComponent<LineRenderer>();
lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
lr.startColor = color;
lr.useWorldSpace = true;
lr.endColor = color;
lr.startWidth = 0.1f;//0.03f;
lr.endWidth = 0.1f;//0.03f;
lr.SetPosition(0, start);
lr.SetPosition(1, end);
}
}


The result is that the line is seen in the scene view window but not in the game view window:

In this line:

pos = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, lr.transform.position.z));


you're using the Z position of the camera itself.

Keep in mind that the Z returned by the method is the distance from the plane normal to the camera forward direction and the Z parameter itself.

In your case, since Camera.main.position.z is -10, and you pass -10 as the Z parameter, the Z returned will be -20.

If you position the camera to Z = 10, then the method will return Z = 20, etc.

So, if the camera is in Z = -10 and the new line renderer has both positions set to Z = -20, it will be behind the camera frustum and not rendered.

• I see I could also change the GameObject myLine = new GameObject(); position to be in front of the camera. But how can I make it automatic to be always in front the camera ? Either the lr position or the myLine position. – Daniel Lip Mar 25 '18 at 4:54
• If your camera never moves, then you can simply provide a specific Z parameter to ScreenToWorldPoint, for example if you want to create the LR in Z =35, just pass 45 as Z, such that 45-10=35. Or just modify the pos.position.z as you wish before adding it to the list. – Galandil Mar 25 '18 at 12:26