【问题标题】:How do I save all generated Lines on the screen如何在屏幕上保存所有生成的行
【发布时间】:2020-05-27 08:22:03
【问题描述】:

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

如何保存所有生成的行?

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

【问题讨论】:

  • "line" 变量在每次调用 CreateLine 时都会被覆盖,那么让它成为本地的,而不是全局的呢?

标签: c# unity3d line renderer


【解决方案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();(我已将其注释掉)。

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

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

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

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

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多