Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

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));
}

スクリーンショット 2015-07-20 14.19.27.png

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 ();
}

スクリーンショット 2015-07-20 14.34.30.png

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();
}

スクリーンショット 2015-07-20 14.57.13.png

kwst
Front Engineer
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした