↓
Code與Infomation源頭:Hide in Inspector
在自定義Unity編輯面板中,其中一個有趣的顯示方式:勾選其中一個Boolean值來決定是否在Inspector上顯示該項目。
使用HideUnlessAttribute.cs與HideUnlessAttributeDrawer.cs以及HideableAttributeDrawer.cs語法後,我們可以這樣寫就會呈現本文章圖片的模式:
public bool StartPositionNoRandom = false;
[HideUnless("StartPositionNoRandom")]
public Vector2 StartPosition;
目前測試結果,不能用這方法來隱藏參數的類型有:
- List
- 你自己設置的Class,你只會讀到一行標頭
修正版本
自定義Class可以顯示的修正,包含要重新計算Height、還有最關鍵的EditorGUI.PropertyField的第四個屬性。
HideableAttributeDrawer class
// --------------------------------
//
// Copyright (C) Rumor Games, LLC. All rights reserved.
// Modified by BearuBox
//
// --------------------------------
using UnityEditor;
using UnityEngine;
///
/// HideableAttributeDrawer class.
///
public abstract class HideableAttributeDrawer : PropertyDrawer
{
///
/// Draws the GUI for the property.
///
/// Rectangle on the screen to use for the property GUI. /// The SerializedProperty to make the custom GUI for. /// The label of this property. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (!this.IsHidden(property))
{
position.height = _GetRealHeight(property, label);
EditorGUI.PropertyField(position, property, label, true);
}
}
///
/// Get the property height in pixels of the given property.
///
/// The SerializedProperty to get height for. /// The label of this property. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
float Height = _GetRealHeight(property, label);
return this.IsHidden(property) ? 0f : Height;
}
///
/// Checks whether the property is supposed to be hidden.
///
/// The SerializedProperty to test. /// True if the property should be hidden.
protected abstract bool IsHidden(SerializedProperty property);
private float _GetRealHeight(SerializedProperty property, GUIContent label)
{
float Height = base.GetPropertyHeight(property, label);
if (property.isExpanded)
{
Height *= (fieldInfo.FieldType.GetFields().Length + 1);
}
return Height;
}
沒有留言:
張貼留言
歡迎大家留言提問,我會答的都會盡力回答!
如果太久沒出現回應就是我又忘記回來看留言了TAT