1
\$\begingroup\$

I have a Line Renderer component with 4 points, I would like to disable and enable the last 2 points at a certain time. My question is, how would I in code (C#) enable and disable individual Line Renderer points?

Thanks in advance!

\$\endgroup\$
2
  • \$\begingroup\$ You can't selectively disable them, but you can assign the points dynamically - so, at the moment you want to "enable" the points, you'd add them to the LineRenderer, and the moment you want to "disable" those points, you'd remove them. You could also play with a shader that clips the line at a given spot, but adding/removing points is probably a simpler place to start. \$\endgroup\$
    – DMGregory
    Feb 12, 2017 at 18:26
  • \$\begingroup\$ Hey, thanks for reply. Could you give me a sample of code to get me on the right track? \$\endgroup\$
    – John Smith
    Feb 12, 2017 at 18:29

1 Answer 1

2
\$\begingroup\$

As mentioned in a comment above, you can't enable or disable individual points in the LineRenderer. But, you can change/add/remove points dynamically, which can get a similar effect.

Here's a sample script that builds a random zig-zag path by adding segments to the end of the line, then progressively chops the line back until it disappears completely.

[RequireComponent(typeof(LineRenderer))]
public class RandomZig : MonoBehaviour {

    LineRenderer _line;

    public int maxSize = 30;

    public float delay = 0.25f;

    // Use this for initialization
    void Start () {
        _line = GetComponent<LineRenderer>();
        StartCoroutine(AddSegments());
    }

    IEnumerator AddSegments()
    {
        float previous = 0f;
        for(int i = 0; i < maxSize; i++)
        {
            _line.SetVertexCount(i + 1);

            float wander = previous + (Random.value - 0.5f) * 2f;

            _line.SetPosition(i, Vector3.forward * i + Vector3.right * wander);
            // Note you can use SetPositions if you need to assign a whole array at once.

            previous = wander;

            yield return new WaitForSeconds(delay);
        }

        StartCoroutine(RemoveSegments());
    }

    IEnumerator RemoveSegments()
    {
        for(int i = maxSize - 1; i > 0; i--)
        {
            _line.SetVertexCount(i);

            yield return new WaitForSeconds(delay);
        }
    }
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Works just as I wanted, however there's a little change in the latest version of Unity where instead of .SetVertexCount(NUMBER), it is .numPositions = NUMBER \$\endgroup\$
    – John Smith
    Feb 12, 2017 at 18:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .