ในตัวอย่างจะเป็นการทำ Property ที่ใช้ในการเช็คว่า Field นั้นต้องมีการใส่ข้อมูล
เริ่มกันเลย
1. ให้ทำการสร้าง Script C# มา 3 files (ตัวอย่างชื่อ RequireAttribute.cs, RequireDrawer.cs และ RequireExample.cs)
2. จากนั้นให้ทำการเปิดไฟล์ RequestAttribute.cs แล้วทำการเพิ่ม
using UnityEngine;
using System.Collections;
// inherite class from PropertyAttribute
public class RequireAttribute : PropertyAttribute
{
// ตัวแปรสำหรับ แสดงข้อความเตือน
public readonly string alertMessage;
public RequireAttribute(string alertMessage)
{
this.alertMessage = alertMessage;
}
}
using UnityEngine;
using UnityEditor;
// inherit from PropertyDrawer
[CustomPropertyDrawer(typeof(RequireAttribute))]
public class RequireDrawer : PropertyDrawer
{
// set ความสูงของ Text
const int textHeight = 16;
const int helpHeight = 30;
// อ้างอิง arequireAttribute
RequireAttribute requireAttribute { get { return ((RequireAttribute)attribute); } }
// set ความสูงของ Property นี้
public override float GetPropertyHeight (SerializedProperty prop, GUIContent label)
{
if (CheckField(prop))
return base.GetPropertyHeight (prop, label)+ helpHeight;
else
return base.GetPropertyHeight (prop, label);
}
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
// set ตำแหน่ง และ ความสูงของ Text Field
Rect textFieldPosition = position;
textFieldPosition.height = textHeight;
// สร้าง Text Field
prop.stringValue = EditorGUI.TextField (textFieldPosition, label, prop.stringValue);
// set ตำแหน่ง และ ความสูงของ Help Message
Rect helpPosition = position;
helpPosition.y += textHeight;
helpPosition.height = helpHeight;
// ตรวจว่า Field ว่างหรือไม่ ถ้าว่างแสดงข้อความเตือน
if(CheckField(property))
{
EditorGUI.HelpBox (helpPosition, RequireAttribute.alertMessage, MessageType.Error);
}
}
// ตรวจว่า Field ว่างหรือไม่
bool CheckField (SerializedProperty prop)
{
return prop.stringValue == "";
}
}
using UnityEngine;
using System.Collections;
public class RequireExample : MonoBehaviour
{
[RequireAttribute("Request Field Name")]
public string name;
}