2Dの線を描画する【Unity】


いくつか方法があったので、まとめます。

LineRenderer

空のGameObject → add component → Line Renderer を選択します。
マテリアルを設定すれば色などを設定できるようになります。

Line.cs
void Start () {
    LineRenderer renderer = gameObject.GetComponent<LineRenderer>();
    // 線の幅
    renderer.SetWidth(0.1f, 0.1f);
    // 頂点の数
    renderer.SetVertexCount(2);
    // 頂点を設定
    renderer.SetPosition(0, Vector3.zero);
    renderer.SetPosition(1, new Vector3(1f, 1f, 0f));
}

GL.LINES

openGLの機能を直接つかって描く方法です。
空のGameObjectに以下のスクリプトを適応します。
lineMaterialには任意のマテリアルをUnity側で設定します。
この方法では線の幅を指定することができないようなので、GL.QUADSでポリゴンを作る必要があります。

GLLine.cs
public Material    lineMaterial;
void OnRenderObject () {
    lineMaterial (0);
    GL.PushMatrix ();
    GL.MultMatrix (transform.localToWorldMatrix);
    GL.Begin (GL.LINES);
    GL.Vertex3 (0f, 0f, 0f);
    GL.Vertex3 (1f, 1f, 0f);
    GL.End ();
    GL.PopMatrix ();
}

Texture2D

これはテクスチャに直接ピクセルを書き込んでいく方法です。
空のGameObject → add component → GUI Texture を選択します。

TextureLine.cs
void Start () {
    // Texture2Dの作成.
    int width  = 256;
    int height = 256;
    Texture2D texture = new Texture2D(width, height);
    GUITexture tex = GetComponent<GUITexture>();
    tex.texture = texture;
    // テクスチャを真ん中に持ってきます
    Rect rect = new Rect();
    rect.Set(0f, 0f, Screen.width, Screen.height);
    tex.pixelInset = rect;

    // テクスチャ描画クラスの作成.
    DrawTexture2D drawTex2D = new DrawTexture2D();
    // テクスチャへ描画開始.
    drawTex2D.Begin(texture);   
    drawTex2D.Clear (new Color(0.0f, 0.0f, 0.0f));
    // 線の描画
    drawTex2D.DrawLine(0, 0, 128, 128, new Color(1f, 0f, 0f));
    // テクスチャへ描画終了.
    drawTex2D.End();
}