Simple tutorial on how to draw lines with mouse in 2D.

Content not available.
Please allow cookies by clicking Accept on the banner

Firstly, create new material and name it “Line” (right click in Assets window?Create?Material). Change it’s Shader to Sprites?Default.

After that it should look like this:

Now create new GameObject in Hierarchy and name it “LineCreator” (right click in Hierarchy window and choose Create Empty). Attach “LineCreator” script to it. To do that click Add Component and choose New Script from the list. Name the script ?LineCreator?, edit it by clicking twice on it in Assets window or by clicking little gear over it in Inspector window and choosing Edit Script option. Change it, so it looks like this:

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

// ? 2018 TheFlyingKeyboard and released under MIT License 
// theflyingkeyboard.net 

public class LineCreator : MonoBehaviour {
  [SerializeField] private GameObject line;
  private Vector2 mousePosition;

  private void Update () {
    if (Input.GetMouseButtonDown(0)) //Or use GetKeyDown with key defined with mouse button
    {
      mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
      Instantiate(line, mousePosition, Quaternion.Euler(0.0f, 0.0f, 0.0f));
    }
  }
}

After that create second GameObject and name it “LineDrawer”. Attach LineRenderer to it – click Add Component and type in the search window “Line Renderer”, choose it and change it’s properties to match the following:

Remember to fill the Materials list field with material that we created. After that add new script to it, named “LineDrawer”:

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

// ? 2018 TheFlyingKeyboard and released under MIT License 
// theflyingkeyboard.net 

public class LineDrawer : MonoBehaviour {
  private LineRenderer line;
  private Vector2 mousePosition;

  [SerializeField] private bool simplifyLine = false;
  [SerializeField] private float simplifyTolerance = 0.02f;

  private void Start () {
    line = GetComponent<LineRenderer>();
  }

  private void Update () {
    if (Input.GetMouseButton(0)) //Or use GetKey with key defined with mouse button
    {
      mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

      line.positionCount++;
      line.SetPosition(line.positionCount - 1, mousePosition);
    }

    if (Input.GetMouseButtonUp(0))
    {
      if (simplifyLine)
      {
        line.Simplify(simplifyTolerance);
      }

      enabled = false; //Making this script stop
    }
  }
}

Note that, the higher the “simplifyTolerance” is the less points the line will have. Next step is to save the “LineDrawer” GameObject as a prefab (drag it from Hierarchy window to Assets window, it should change font color to blue in the Hierarchy) and delete it from scene. After the object was saved fill the Line field in the “LineCreator” GameObject in the Hierarchy using the prefab that was created. 

Everything should be working now.

Thank you for reading ?.



Unity 2D C# Drawing Lines With Mouse
Tagged on:         

6 thoughts on “Unity 2D C# Drawing Lines With Mouse

  • February 26, 2018 at 7:36 am
    Permalink

    The code doesnt work me. Cant see the line. All the positions of the instantiated line are (0,1,0).

    Reply
  • April 22, 2018 at 1:45 am
    Permalink

    Eyal, the same thing happens to me, but I think I?ve solved the problem. mousePosition is a Vector2, but in order to covert it to a World position, you need it to be a Vector3.

    So in the LineDrawer script, mousePosition must declared a Vector3 (not Vector2):

    //private Vector2 mousePosition;
    private Vector3 mousePosition;

    And in the Update function, do this:
    if (Input.GetMouseButton(0))
    {
    mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    mousePosition.z = 1.0f;
    line.positionCount++;
    line.SetPosition(line.positionCount -1, mousePosition);
    }
    You need to assign a value for the z component. Note that if your camera is in Perspective mode, the value for mousePosition.z will affect the thickness of the line being drawn (but no effect on line thickness if the camera is Orthographic).

    That should do it!

    Reply
  • April 22, 2018 at 7:03 pm
    Permalink

    FOR THIS TO WORK YOU MUST MAKE SURE THAT THE PROJECTION IS SET TO ORTHOGRAPHIC RATHER THAN PERSPECTIVE IN THE INSPECTOR WHEN THE MAIN CAMERA IS SELECTED

    SORRY FOR SHOUTING IN CAPITALS, MY CAPS LOCK IS STUCK ON

    Reply
  • May 12, 2018 at 9:22 pm
    Permalink

    Hey everyone, I was really hyped as I saw the video for this tutorial, because I was looking for something like this for a long time now. Sadly Unity is kinda salty and gives me some errors.
    In the 2nd script (LineDrawer) it says, that positionCount in line 24&25 ..

    error CS0117: UnityEngine.LineRenderer does not contain a definition for positionCount ..

    ..same error for Simplify in line 32.
    I have read the previous comments and already changed those parts in the script ..but still have those errors.
    Does someone has an idea what could have possibly gone wrong? ..
    I’m sorry, but I’m a total noob, when it come to programming, so I hope someone has an idea whats going on here t-t ..

    Reply
  • July 11, 2018 at 9:37 am
    Permalink

    this scripts let me draw at once. when i click again to mouse, then it does not drawing line. how can i fix it?

    Reply
    • October 10, 2019 at 9:16 am
      Permalink

      Draw once as on GetMouseButtonUp he disable the whole script, you can comment this line, and will see the you can continue drawing from the end point of the previous line.
      if you need to draw separate lines you can add another script that instantiate line on GetMouseButton.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close