LoginSignup
1
1

More than 3 years have passed since last update.

3D空間上の範囲をPixelで指定する。

Posted at

May-20-2019 01-36-05.gif

スクリーンショット 2019-05-20 1.38.38.png

NGUIのWidgetのように範囲を指定する機能を最小限で作りたかったので作成

SpriteRendererとは別に範囲を設定するに使えるんじゃないかと思います

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

#if UNITY_EDITOR
using UnityEditor;

[CustomEditor(typeof(Rectangle))]
public class RectangleEditor : Editor{

    SerializedProperty pixelsPerUnitProperty;
    SerializedProperty boundsProperty;

    Rectangle rectangle;

    void OnEnable()
    {
        rectangle = target as Rectangle;
        pixelsPerUnitProperty = serializedObject.FindProperty("pixelsPerUnit");
        boundsProperty = serializedObject.FindProperty("bounds");
    }

    public override void OnInspectorGUI(){
        serializedObject.Update();
        EditorGUILayout.PropertyField(pixelsPerUnitProperty);
        using(new EditorGUILayout.HorizontalScope()){
            GUILayout.FlexibleSpace();
            var oldLabelWidth = EditorGUIUtility.labelWidth;
            EditorGUIUtility.labelWidth = 20;
            int oldWidth = (int)(rectangle.bounds.size.x * rectangle.pixelsPerUnit);
            var width = EditorGUILayout.IntField("W", oldWidth, GUILayout.MaxWidth(100));
            int oldHeight = (int)(rectangle.bounds.size.y * rectangle.pixelsPerUnit);
            var height = EditorGUILayout.IntField("H", oldHeight, GUILayout.MaxWidth(100));

            if(width != oldWidth || height != oldHeight){
                rectangle.bounds.size = new Vector3(width, height, 0f) / rectangle.pixelsPerUnit;
                EditorUtility.SetDirty(rectangle);
            }
            EditorGUIUtility.labelWidth = oldLabelWidth;
        }
        serializedObject.ApplyModifiedProperties();
    }
}
#endif

public class Rectangle : MonoBehaviour {
    public Bounds bounds;

    public int pixelsPerUnit = 100;

    /// <summary>
    /// Callback to draw gizmos that are pickable and always drawn.
    /// </summary>
    void OnDrawGizmos () {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube (this.transform.position + bounds.center, bounds.size);
    }
}


1
1
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
1
1