ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DrawCircle

Draw circles on Unity GameObjects

Source

using UnityEngine;

public static class GameObjectEx
{
    public static void DrawCircle(this GameObject container, float radius, float lineWidth)
    {
        var segments = 360;
        var line = container.AddComponent<LineRenderer>();
        line.useWorldSpace = false;
        line.startWidth = lineWidth;
        line.endWidth = lineWidth;
        line.positionCount = segments + 1;

        var pointCount = segments + 1; // add extra point to make startpoint and endpoint the same to close the circle
        var points = new Vector3[pointCount];

        for (int i = 0; i < pointCount; i++)
        {
            var rad = Mathf.Deg2Rad * (i * 360f / segments);
            points[i] = new Vector3(Mathf.Sin(rad) * radius, 0, Mathf.Cos(rad) * radius);
        }

        line.SetPositions(points);
    }
}

Example

var go1 = new GameObject { name = "Circle" };
go1.DrawCircle(1, .02f);

var go2 = new GameObject { name = "Circle2" };
go2.transform.Rotate(30f, 0, 0);
go2.transform.Translate(new Vector3(.5f, 0, 0));
go2.DrawCircle(1.5f, .02f);

Author: Loek van den Ouweland

Submitted on: 30 apr. 2018

Language: C#

Type: GameObject

Views: 4200