如何在Unity Inspector中以只读形式显示私有字段(仿Debug模式)
实现Unity私有字段Inspector只读显示的几种方法
下面分享几种能让私有字段在Inspector里只读展示的方案,效果和Debug模式下的私有字段一致:
方法1:自定义ReadOnly属性(无插件)
这是最轻量化的方案,不用依赖第三方插件:
- 先创建一个属性类(随便放哪个文件夹都行):
using UnityEngine; public class ReadOnlyAttribute : PropertyAttribute { }
- 再创建对应的属性绘制器,必须放在Editor文件夹下:
using UnityEditor; using UnityEngine; [CustomPropertyDrawer(typeof(ReadOnlyAttribute))] public class ReadOnlyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // 临时禁用GUI交互,绘制完再恢复 GUI.enabled = false; EditorGUI.PropertyField(position, property, label, true); GUI.enabled = true; } }
- 用的时候给私有字段加两个特性就搞定:
public class TestScript : MonoBehaviour { [SerializeField, ReadOnly] private int _privateReadOnlyValue = 10; }
方法2:自定义Editor脚本(灵活可控)
如果需要更复杂的逻辑(比如只在运行时只读,编辑时可改),可以写自定义Editor:
- 先给脚本里的私有字段加上
[SerializeField]:
public class TestScript : MonoBehaviour { [SerializeField] private int _privateReadOnlyValue = 10; }
- 在Editor文件夹下创建对应的Editor脚本:
using UnityEditor; using UnityEngine; [CustomEditor(typeof(TestScript))] public class TestScriptEditor : Editor { private SerializedProperty _privateField; private void OnEnable() { // 通过字段名找到序列化的私有字段 _privateField = serializedObject.FindProperty("_privateReadOnlyValue"); } public override void OnInspectorGUI() { // 禁用GUI后绘制字段,确保无法修改 GUI.enabled = false; EditorGUILayout.PropertyField(_privateField); GUI.enabled = true; // 提交属性修改,必须调用 serializedObject.ApplyModifiedProperties(); } }
方法3:用现成插件快速实现
如果项目里已经在用第三方Inspector插件,比如Odin Inspector,直接加两个特性就行,零代码:
public class TestScript : MonoBehaviour { [ShowInInspector, ReadOnly] private int _privateReadOnlyValue = 10; }
以上几种方案都能实现你要的效果:私有字段在Inspector里可见,但完全无法修改,和Debug模式的展示逻辑一致。
内容的提问来源于stack exchange,提问作者나만없어 고양이
相关产品推荐
相关产品推荐

