Drawing lines folling user input using line renderer.
Hello,
I have been stuck on a problem for a couple of days and I cant figure it out. I am new to unity and c# but understand enough to muddle my way through. Basically I am trying to draw a line on the screen that eventually my Sprite (Plane) will follow. The line needs to begin only at the sprite and end anywhere else. However I am having trouble creating the loop to add the vector 3 to the line renderer. I have got the basics to work however it only work when the key is pressed down. My latest attempt involves a while loop but that seems to put me in an infinite loop and it crashes.
There a re a couple of other small issues I could do with some help on that I will list below, but above is the main one.
Do I increasing the index of the line renderer based on how many points are created or just spawn each line renderer with say an index on 100? Could this be done in real time?
Vector3.Distance(_previous, _current) < 0.1f, not sure if this is correct or if the value has to be in a vector 3 format.
I am getting a few strange errors for _previous and _positions. drawline.Position is never assigned to and will always have its default value null. However i can see in the editor that on each mouse click it is updating the line renderer so I'm not sure what is going on?
I know this is a lot but I could do with a nudge in the right direction or pointing to some reading. Any help will be greatly appreciated.
Cheers
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Drawline : MonoBehaviour
{
private Plane _plane;
private LineRenderer _lRend;
public Vector3 _previous;
int vertexCount = 0;
public List<Vector3> _positions;
private Vector3 _current;
bool _drawline = false;
private void Start()
{
_plane = GameObject.Find("Plane").GetComponent<Plane>();
LineRenderer _lRend = _plane.GetComponent<LineRenderer>();
}
void Update()
{
if (Input.GetMouseButtonDown(0) || Input.touchCount > 0 )
{
Vector3 pos = Input.mousePosition;
Collider2D hitCollider = Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(pos));
if (hitCollider != null && hitCollider.CompareTag("Plane"))
{
Debug.Log("This is player");
LineRenderer _lRend = _plane.GetComponent<LineRenderer>();
_drawline = true;
while (_drawline == true)
{
_current = Input.mousePosition;
if (Vector3.Distance(_previous, _current) < 0.1f) { return; }
vertexCount = ++vertexCount;
_positions.Add(_current);
for (int i = 0; i < vertexCount; i++)
{
_lRend.SetPosition(i, _positions[i]);
}
if (Input.GetMouseButtonUp(0))
{
_drawline = false;
}
}
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612194601im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make a surface glow when its hit by a laser. 0 Answers
LineRender Not Detecting Collison 0 Answers
LineRenderer Raycast Gun Bug 1 Answer
X/Y/Z distance 1 Answer
Making Raycast line visible 2 Answers