LineRendererで割ときれいな線を描いてみる


はじめに

この記事は以下のサイトの記事を参考にさせていただいてます
https://qiita.com/7of9/items/3750d30590e3efcfd389

注意

最適化までは行っていないのでその点はご注意ください

仕様的なもの

  • 受け渡されたor設定された座標をつなぎ合わせて1本のきれいな線を描く
  • Z軸は使用しない

コード部分

DrawLine.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrawLineUI : MonoBehaviour
{
    [SerializeField] private Material lineMaterial;  // 線に使うマテリアル
    [SerializeField] private Color lineColor;   // 線の色
    [SerializeField] private float lineWidth;    // 線の太さ
    [SerializeField] private List<GameObject> objList;    
    [SerializeField] private List<Vector2> positionObjList;

    // 追加されたゲームオブジェクトのリスト
    private List<GameObject> addGameObjectList = new List<GameObject>();

    void Start () 
    {
        DrawLine();
    }

    private void DrawLine()
    {
        List<Vector3> positionList = new List<Vector3>();
        positionList = StoringVector2ToVector3(positionObjList);
        for(int index = 0;index < positionObjList.Count - 1;++index)
        {
            CreateLine(positionObjList,index);
        }
    }

    // Vector2のリストを持ってきて、SetActiveを確認しながらCreateLineに使うListに格納していく
    private List<Vector3> StoringVector2ToVector3(List<Vector2> positionObjList)
    {
        List<Vector3> positionList = new List<Vector3>();
        for(int index=0;index<positionObjList.Count;++index)
        {
             if(objList[index].active == false)
             {   //gameObjectが設定されていない場合に飛ばす
                 continue;
             }
         }
        positionObjList.Add(positionList[index]);

        return positionObjList;
    }

    // 新しいオブジェクトを作ってLineRenderともろもろの設定を突っ込むとこ
    private void CreateLine(List<Vector3> vec3List, int indexNum)
    {
        List<Vector3> myPoint = new List<Vector3>();    // LineRendererのPositionを設定するのに使用
        for(int idx = 0; idx < 2; idx++) 
        {
            myPoint.Add(new Vector3(vec3List[indexNum + idx].x, vec3List[indexNum + idx].y, 0.0f));
        }
        // 生成するオブジェクト名
        GameObject newLine = new GameObject ("Line"+addGameObjectList.Count);   
        addGameObjectList.Add(newLine);
        LineRenderer lineRenderer = newLine.AddComponent<LineRenderer> ();
        lineRenderer.useWorldSpace = false;
        lineRenderer.SetVertexCount(2);
        lineRenderer.SetWidth (lineWidth, lineWidth);
        lineRenderer.SetColors(lineColor,lineColor);    // 色の設定
        if(lineMaterial != null)
        {
            lineRenderer.material = lineMaterial;
        }
        Vector3 startVec = myPoint[0];
        Vector3 endVec   = myPoint[1];
        lineRenderer.numCapVertices = 90;
        lineRenderer.SetPosition (0, startVec);
        lineRenderer.SetPosition (1, endVec);
    } 
}

最後に

LineRenderer複雑ですね~
もうちょっと簡単に線を実装できたらいいんですけど・・・・