Drawing Connected Straight Lines on a Surface Using Line Renderer


LineCreator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System.Linq;
using UnityEngine;
 
public class LineCreator : MonoBehaviour
{
    LineRenderer lineRenderer;
    RaycastHit hit;
 
    void Awake()
    {
        lineRenderer = gameObject.AddComponent<LineRenderer>();
        lineRenderer.startWidth = 0.1f;
        lineRenderer.material = Resources.FindObjectsOfTypeAll<Material>().SingleOrDefault(m => m.name == "Line");
        lineRenderer.positionCount = 0;
    }
 
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
            {
                AddLinePoints(hit.point + hit.normal.normalized * 0.1f);
            }
        }
 
        if (Input.GetMouseButtonDown(1))
        {
            ClearLinePoints();
        }
    }
 
    void AddLinePoints(Vector3 point)
    {
        lineRenderer.positionCount++;
        lineRenderer.SetPosition(lineRenderer.positionCount-1, point);
    }
 
    void ClearLinePoints()
    {
        lineRenderer.positionCount = 0;
    }
}