4
6

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 5 years have passed since last update.

【Unityエディター拡張】シェーダーを使ってInspectorのプレビュー領域に円を描画させてみた

4
Last updated at Posted at 2016-02-17

※この記事で使っているUnityのバージョンは Unity5.2.1p3 です。

image

はじめに

OnPreviewGUIを利用することでプレビュー領域の描画処理を自分で作ることができます.
そこで円を描画させるカスタムシェーダを作成し、これをプレビュー領域に適用して円を描画させてみました。

空のMonoBehaviourスクリプトを作成

以下のスクリプトを作成してプロジェクト内に入れます.
作成したスクリプトはシーン内の適当なオブジェクトにアタッチします.

NewBehaviourScript.cs
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{

}

プレビュー領域の描画処理を実装する

以下のスクリプトを作成してEditorフォルダ内へ入れます.

NewBehaviourScriptEditor.cs
using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(NewBehaviourScript))]
public class NewBehaviourScriptEditor : Editor
{
    private Material material = null;
    public override bool HasPreviewGUI()
    {
        return true;
    }

    public override GUIContent GetPreviewTitle()
    {
        return new GUIContent("ほげ");
    }
    
    public override void OnPreviewGUI(Rect r, GUIStyle background)
    {
        if (material == null)
        {
            // カスタムシェーダからMaterialを作成
            Shader shader = Resources.Load<Shader>("Shader/Ring");
            this.material = new Material(shader);
        }

        base.OnPreviewGUI(r, background);
        Graphics.DrawTexture(r, Texture2D.whiteTexture, this.material);
    }
}

円を描画するカスタムシェーダの作成

以下のシェーダを作成して
ファイルパスがAssets/Resources/Shader/Ring.shaderとなるように
配置します.

Ring.shader
Shader "Unlit/Ring"
{
	Properties
	{
		_MainTex("Texture", 2D) = "white" {}
	}

		SubShader
	{
		Tags{ "RenderType" = "Opaque" }

		Pass
	{
		CGPROGRAM
# pragma vertex vert
# pragma fragment frag

# include "UnityCG.cginc"

	struct appdata
	{
		float4 vertex : POSITION;
		float2 uv : TEXCOORD0;
	};

	struct v2f
	{
		float2 uv : TEXCOORD0;
		float4 vertex : SV_POSITION;
	};

	sampler2D _MainTex;
	float4 _MainTex_ST;

	v2f vert(appdata v)
	{
		v2f o;
		o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
		o.uv = TRANSFORM_TEX(v.uv, _MainTex);
		return o;
	}

	fixed4 frag(v2f i) : SV_Target
	{
		// 円の半径
		fixed r = 0.3;

	    // 円の中心
   	    fixed2 center = fixed2(0.5, 0.5);

	    return step(r, length(i.uv - center));
	}
		ENDCG
	}
	}
}

完成

image
NewBehaviourScriptアタッチしたオブジェクトを選択するとプレビュー領域に円が表示されます.

参考

Editor.OnPreviewGUI - Unity - スクリプトリファレンス
http://docs.unity3d.com/ja/current/ScriptReference/Editor.OnPreviewGUI.html

4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?