Custom Attributes

Hi :slight_smile:

I’m reading some tutos about Custom Properties, Custom Property Drawers and Custom Attributes, but I have some problems to use them.

Unity Manual - Property Drawers :

A post in Unity blogs :
http://blogs.unity3d.com/2012/09/07/property-drawers-in-unity-4/

I made my own RangeAttribute (like in the tuto of the first link), but I can’t use it in my classes.

Here’s my attribute and drawer script :

using UnityEngine;
using UnityEditor;

public class Range2Attribute : PropertyAttribute
{
    private        float        m_Min        = 0.0f;
    private        float        m_Max        = 1.0f;

    private void MyRangeAttribute(float _Min, float _Max)
    {
        m_Min = _Min;
        m_Max = _Max;
    }

    public float Min
    {
        get { return m_Min; }
    }

    public float Max
    {
        get { return m_Max; }
    }
}

[CustomPropertyDrawer(typeof(Range2Attribute))]
public class Range2Drawer : PropertyDrawer
{
    public override void OnGUI(Rect _Position, SerializedProperty _Property, GUIContent _Label)
    {
        Range2Attribute range = attribute as Range2Attribute;

        if(_Property.propertyType == SerializedPropertyType.Float)
        {
            EditorGUI.Slider(_Position, _Property, range.Min, range.Max);
        }

        else if(_Property.propertyType == SerializedPropertyType.Integer)
        {
            EditorGUI.IntSlider(_Position, _Property, (int)range.Min, (int)range.Max);
        }

        else
        {
            EditorGUI.LabelField(_Position, _Label.text, "Use range with float or int.");
        }
    }
}

And here’s how I’m using it :

using UnityEngine;

public class TestCustomAttribute : MonoBehaviour
{
    [Range2(0.0f, 4.0f)]
    private float m_Property = 0.0f;
}

If you test them, you’ll see two errors in the editor’s console that say “type or namespace name ‘Range2/Range2Attribute’ could not be found”.

I think I just forget something, but I don’t know what… Can someone help me ?
Note that I’m working on Unity 5.1.0f3.

You didn’t specify the constructor correctly, this is how it should be done:

public class Range2Attribute : PropertyAttribute
{
    private        float        m_Min        = 0.0f;
    private        float        m_Max        = 1.0f;

    public Range2Attribute(float _Min, float _Max)
    {
        m_Min = _Min;
        m_Max = _Max;
    }

Ops, sorry, it’s just an error when I copied my code. It still doesn’t work with the same scripts but the right constructor.

But I found the answer : I put my Attributes scripts in the Editor folder, so they can’t be seen.

2 Likes