'Draw a Line on Canvas With Mouse Position Unity 3D
I followed a tutorial to draw a line using mouse position, the line will be drawn inside the canvas. But when running it, the line didn't drawn! and it gives me this error:
NullReferenceException: Object reference not set to an instance of an object
What's wrong in my code?
Here's the script:
public GameObject Line;
GameObject CurrentLine;
LineRenderer linerenderer;
private List<Vector2> FingerPositions;
public Canvas Can;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
CreateLine();
}
if (Input.GetMouseButton(0))
{
Vector2 tempfingerpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (Vector2.Distance(tempfingerpos, FingerPositions[FingerPositions.Count - 1]) > 0.1f)
{
UpdateLine(tempfingerpos);
}
}
}
void CreateLine()
{
CurrentLine = Instantiate(Line, Vector3.zero, Quaternion.identity);
linerenderer = CurrentLine.GetComponent<LineRenderer>();
FingerPositions.Clear();
FingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
FingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
linerenderer.SetPosition(0, FingerPositions[0]);
linerenderer.SetPosition(0, FingerPositions[1]);
CurrentLine.transform.SetParent(Can.transform, false);
}
void UpdateLine(Vector2 NewFingerPos)
{
FingerPositions.Add(NewFingerPos);
linerenderer.positionCount ++;
linerenderer.SetPosition(linerenderer.positionCount - 1, NewFingerPos);
}
Solution 1:[1]
My suggestion is to try first to draw line renderer with fixed positions(You can add two empty objects and then draw line renderer between those objects). And if that works, then move to the logic with fingers. Keep in mind that you can't see line renderer if you are using screen space overlay, so you must use Canvas - World Space to see it over the canvas.
Solution 2:[2]
replace this private List FingerPositions; with this
private List<Vector2> FingerPositions = new List<Vector2>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Branko Rizni? |
Solution 2 | ahm-birawi |