Search code examples
c#unity-game-enginelinerenderer

How do I save all generated Lines on the screen


I have two moving Objects and want to connect them with multiple lines. The Lines will be drawn, but disappearing when a new one is created.

How can I save all generated lines ?

void CreateLine()
{
    line = new GameObject("Line" + currLines).AddComponent<LineRenderer>();
    line = GetComponent<LineRenderer>();
    line.SetPosition(0, Pos1);
    line.SetPosition(1, Pos2);
    line.startColor = Color.white;
    line.endColor = Color.white;
    line.startWidth = 5;
    line.endWidth = 5;
    line.positionCount = 2;
    line.sortingOrder = 2;
    line.useWorldSpace = true;
    currLines++;
}

void Start()
{
    Pos1 = GameObject.FindGameObjectWithTag("Pos1");
    Pos2 = GameObject.FindGameObjectWithTag("Pos2");

    InvokeRepeating("CreateLine", 0, 0.05f);
}

Solution

  • Use this code:

    public class LinesCreator : MonoBehaviour
    {
       LineRenderer line;
       GameObject Pos1, Pos2;
       int currLines=0;
    
       Vector3 pos1, pos2;
    
       void CreateLine()
       {
           // To avoid creating multiple lines in the same positions.
           if (Pos1.transform.position == pos1 && Pos2.transform.position == pos2)
            return;
    
        line = new GameObject("Line" + currLines).AddComponent<LineRenderer>();
        //line = GetComponent<LineRenderer>(); // This will return the GameObject's line renerer, not the new GameObject's line rendere
    
           pos1 = Pos1.transform.position;
           pos2 = Pos2.transform.position;
           line.SetPosition(0, pos1);
           line.SetPosition(1, pos2);
           line.startColor = Color.white;
           line.endColor = Color.white;
           line.startWidth = 0.7f;
           line.endWidth = 0.7f;
           line.positionCount = 2;
           line.sortingOrder = 2;
           line.useWorldSpace = true;
           currLines++;
       }
    
       void Start()
       {
           Pos1 = GameObject.FindGameObjectWithTag("Pos1");
           Pos2 = GameObject.FindGameObjectWithTag("Pos2");
    
           InvokeRepeating("CreateLine", 0, 0.05f);
       }
    }
    

    The changes I made:

    First of all, for the program to work as you want is to, remove line = GetComponent(); (I commented it out).

    What this line does is to set line to the gameObject's lineRenderer (the gameObject who has the script on it).

    We don't want that because we want the line to be on the new gameObject.

    Second, I add a condition that helps you not to create line you don't need.

    I did this by compering the last position and the current positions, if both of them (the objects) didn't move - you don't need do draw a new line.