0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

3Dマークアップテキストを簡単に作れるエディタをUnityで作る(簡易版)

Posted at

目的

テキストエディタで頑張るの辛いので、簡単にマークアップが作れる仕組みを、とりあえずな感じで作る。

コード

Unity Editorを優秀な?3Dコンポーザーとして使ってしまおうという話。
image.png
こんなヒエラルキーを作っておいて、
image.png
適当にこんな風になっているとする。

コードを書く。基底クラスとして以下のクラスを作る。

Node.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Node : MonoBehaviour
{
    public virtual string toML()
    {
        string mlResult = "";
        for(int i = 0; i < gameObject.transform.childCount; i++)
        {
            mlResult += gameObject.transform.GetChild(i).gameObject.GetComponent<Node>().toML();
        }

        return mlResult;
    }

    protected string toColorString(Color color)
    {
        return ((byte)(color.r * 255)).ToString("X2") + ((byte)(color.g * 255)).ToString("X2") + ((byte)(color.b * 255)).ToString("X2");
    }
}

各プリミティブの種類ごとに、以下のようなクラスをそれぞれ作る。

Cube.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cube : Node
{
    public override string toML()
    {
        string ret = "";

        ret += "<a-box x=" + gameObject.transform.position.x +
            " y=" + gameObject.transform.position.y +
            " z=" + gameObject.transform.position.z +
            " size=" + gameObject.transform.localScale.x +
            " color=#" + toColorString(gameObject.GetComponent<MeshRenderer>().material.color) +
            ">";
        ret += base.toML();
        ret += "</a-box>";

        return ret;
    }
}

省略するが他のも。
そして、Rootにバインドした以下のコンポーネントでDebug.Logに吐く。

Kick.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Kick : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(gameObject.GetComponent<Node>().toML());
    }
}

結果

Debug.Logで吐いてるので、コンソールからコピペ。

<a-box x=0 y=0 z=0 size=1 color=#FA0303><a-sphere x=0 y=0.79 z=0.71 r=0.5 color=#000000><a-text x=0.77 y=0.79 z=-1.24 size=1 color=#FFFFFF>Hello World</a-text></a-sphere><a-cylinder x=-0.96 y=0.64 z=-1.18 height=2 r=0.5 color=#FFFFFF></a-cylinder></a-box>

できた。
取り急ぎの超簡易版なので、そのうちもっといい形を考える。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?