9/2/2016





Looks like Unity came in help just at the right time with the new beta version (5.5.0) introducing a way better LineRenderer component!

How does the new component work? It's really simple!

You create some points that Unity connects to eachother to create a line and the color is a gradient (can be as simple as 1 or 2 colors).


First of all, add the LineRenderer component to a GameObject.

To render the line we'll need to:

• set a material (appearance of the line)

• set a width curve (the width of the line)

• set the position of the line points

• set a start and end color or alternatively a gradient


Note: set the colors of the line after setting the other properties otherwise you might have the end color set as white even if you set it to something else.





You can modify those properties in the inspector (image above) or even better in the code!


Let's see an example script to prepare the line and make it work on touchscreen:

public AnimationCurve lineWidthCurve; //a width curve that you set in the inspector
public Material lineRendererMaterial; //a material of your choice that you can set in the inspector
GameObject lineGO; //this is the GameObject that will have the LineRenderer component
LineRenderer lineRenderer; //our LineRenderer component
int n = 0; //current number of line positions

void Start() {
    lineGO = new GameObject("Line");
    lineGO.AddComponent<LineRenderer>();

    lineRenderer = lineGO.GetComponent<LineRenderer>();

    //below we set the necessary properties
    lineRenderer.material = lineRendererMaterial;
    lineRenderer.widthCurve = lineWidthCurve;
    lineRenderer.numPositions = 0; //numPositions is the number of positions (the points that make our line)

    lineRenderer.startColor = Color.white;
    lineRenderer.endColor = Color.cyan;
}

void Update() {
   if(Input.touchCount > 0) { //if we're touching the screen
       Touch touch = Input.GetTouch(0); //get the current touch input

       Vector3 mPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15); //get the position of the touch
       Vector3 vertexPos = Camera.main.ScreenToWorldPoint(mPosition); //convert the position of the touch to world coordinates

       if(touch.phase == TouchPhase.Moved) { //if the touch is moving
              lineRenderer.numPositions = n+1; //set the number of positions
              //the line below is used to get neat round corners, we set the number of the corners to the number of the points
              lineRenderer.numCornerVertices = lineRenderer.numPositions;
              lineRenderer.SetPosition(n, vertexPos); //set the position of the point (or vertex) that is at the n index

              n++; //increase number of points
       }    
    }
}

Attach the script to any GameObject, create a curve in the inspector and assign a material and you're ready to go!

Leave a comment if you have anything to ask.