LoginSignup
0
0

More than 3 years have passed since last update.

[Unity] Inspector上でVector3の各成分を(min,max)に制限する

Posted at

Inspector上でVector3の各成分を(0,1)に制限するの続きです。
パラメータを追加することで(0,1)だけではなく(min,max)にすることも可能です。

UserAttributes.cs
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// Vector2/3を(min.max)に制限する <-<summary>を入れるとマウスオーバーで説明が出ます
/// </summary>
public class ClampVectorAttribute : PropertyAttribute {
    public float min;
    public float max;
    public ClampVectorAttribute(float min, float max)
    {
        this.min = min;
        this.max = max;
    }
}

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(ClampVectorAttribute))]
public class ClampVectorDrawer : PropertyDrawer
{
    // Necessary since some properties tend to collapse smaller than their content
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return EditorGUI.GetPropertyHeight(property, label, true);
    }

    // Draw a disabled property field
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        ClampVectorAttribute attr = (ClampVectorAttribute)attribute;
        switch (property.type)
        {
            case "Vector2":
                property.vector2Value = new Vector2(
                    Mathf.Clamp(property.vector2Value.x, attr.min,attr.max),
                    Mathf.Clamp(property.vector2Value.y, attr.min, attr.max)
                );
                break;
            case "Vector3":
                property.vector3Value = new Vector3(
                    Mathf.Clamp(property.vector3Value.x, attr.min, attr.max),
                    Mathf.Clamp(property.vector3Value.y, attr.min, attr.max),
                    Mathf.Clamp(property.vector3Value.z, attr.min, attr.max)
                );
                break;
        }
        EditorGUI.PropertyField(position, property, label, true);
    }
}
#endif

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