lineRenderer with more points

With “LineRenderer” I’m trying to create a line connecting the various items that I’ve clicked in the following order. My problem is that at first click the line starts from the bottom.
This is my script ( The main camera has is the script that the component Line Renderer)

void Update ()
  {
    if(Input.GetKey(KeyCode.Mouse0))
  {
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  RaycastHit hit;

  if (Physics.Raycast(ray, out hit))
  {
  if(!positions.Contains(hit.transform.position))
  {
  i++;
   
  positions.Add(hit.transform.position);
  DrawLine(hit);
   
  }
   


  }
  }
   }

  void DrawLine(RaycastHit hit)
  {
  l = this.GetComponent<LineRenderer>();
  l.SetVertexCount(positions.Count);
  l.SetWidth(0.5f, 0.5f);

  for (int i = 0; i < positions.Count-1; i++)
  {
   
  l.SetPosition(i, positions[i+1]);
  }
  }


I bet the LineRenderer uses world points not screen points, you will need to convert before adding points to it.

1 Like

because I have to redeem points? render the line must go from one to another gameobject

Is the line set to local space? Sounds like you need world space here Unity - Scripting API: LineRenderer.useWorldSpace
also:

  for (int i = 0; i < positions.Count-1; i++) // Why count - 1?
  {
      l.SetPosition(i, positions[i+1]); // should it not be just i? Why i +1?
  }

  // I think you want
  for (int i = 0; i < positions.Count; i++)
  {
      l.SetPosition(i, positions[i]);
  }

he’s not using screen points…

have you exposed positions so you can see it’s content in the inspector? how is it initialsed? (I’m assuming it’s a list)

… hold on, SetVertexCount is now set to obsolete… if they’ve changed it to work out the counts based on the positions being provided it might have some interesting “handling” of a 1 point “line” (lines require two points).

also line renderers have “SetPositions” which is far more efficient for setting the whole line in one go without the need for that for loop.

no, is set to world space