DarwinIcesurfer
DarwinIcesurfer

Reputation: 1133

Unity LineRenderer disconnected segments?

It is possible for a single LineRenderer to create multiple disconnected line segments? I need to create multiple line segments that will all change color at the same time. I have tried to create a positions array with the segments separated by Vector3.positiveInfinity, but that didn't work.

(Attach this class to an empty gameObject)

using System.Collections.Generic;
using UnityEngine;

public class CreateSegments : MonoBehaviour
{
    public GameObject board;
    private List<(Vector3, Vector3)> endPoints;
    private int numLines = 8;
    private float radius = 5;
    private float lineLength = 3;
    private LineRenderer lineRenderer;

    private void Awake()
    {
        board = new("Board");
        board.transform.SetParent(transform);
        lineRenderer = board.AddComponent<LineRenderer>();
    }

    void Start()
    {
        endPoints = new List<(Vector3, Vector3)>();

        for (int i = 0; i < numLines; i++)
        {

            // Calculate the angle of the tic
            float angle = i * 360f / numLines;
            float angleInRadians = angle * Mathf.Deg2Rad;



            Vector3 startPos = board.transform.position + new Vector3(
                Mathf.Sin(angleInRadians),
                Mathf.Cos(angleInRadians),
                0f
                ) * (radius - lineLength);

            var endPos = startPos + new Vector3(
                Mathf.Sin(angleInRadians),
                Mathf.Cos(angleInRadians),
                0f
                ) * lineLength;

            endPoints.Add((startPos, endPos));


        }
        // Create a ticPositions array to hold the pairs of points plus Vector3.positiveInfinity
        Vector3[] positions = new Vector3[endPoints.Count * 3];

        // Turn the ticPositions list into an array for input into lineRenderer
        int iPoint = 0;
        foreach ((Vector3, Vector3) tuple in endPoints)
        {
            positions[iPoint] = tuple.Item1;
            positions[iPoint + 1] = tuple.Item2;
            positions[iPoint + 2] = Vector3.positiveInfinity;

            iPoint += 3;
        }
        lineRenderer.positionCount = positions.Length;
        lineRenderer.SetPositions(positions);
    }


    void Update()
    {
        
    }
}

Upvotes: 0

Views: 196

Answers (1)

Dimitar
Dimitar

Reputation: 4801

As of Unity 6 this is not the case. There is also a Unity or two on the topic: post, or post. Adding multiple LineRenderer components to a single GameObject results in:

Can't add component 'LineRenderer' to [GameObject] because such a component is already added to the game object!

Unfortunately, one should indeed create a separate GameObject for each line segment to be drawn by a different LineRenderer.

Upvotes: 0

Related Questions