0

我有两个移动的对象,想用多条线连接它们。线条将被绘制,但在创建新线条时会消失。

如何保存所有生成的行?

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);
}
4

1 回答 1

1

使用此代码:

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);
   }
}

我所做的更改:

首先,要使程序按您的意愿工作,请删除line = GetComponent(); (我把它注释掉了)。

这条线的作用是将线设置为游戏对象的 lineRenderer(上面有脚本的游戏对象)。

我们不希望这样,因为我们希望这条线位于新的游戏对象上。

其次,我添加了一个条件,帮助您不要创建不需要的行。

我通过比较最后一个位置和当前位置来做到这一点,如果它们(对象)都没有移动 - 你不需要画一条新线。

于 2020-05-27T10:21:16.513 回答