You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Unity Inspector中以只读形式显示私有字段(仿Debug模式)

实现Unity私有字段Inspector只读显示的几种方法

下面分享几种能让私有字段在Inspector里只读展示的方案,效果和Debug模式下的私有字段一致:

方法1:自定义ReadOnly属性(无插件)

这是最轻量化的方案,不用依赖第三方插件:

  1. 先创建一个属性类(随便放哪个文件夹都行):
using UnityEngine;

public class ReadOnlyAttribute : PropertyAttribute { }
  1. 再创建对应的属性绘制器,必须放在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;
    }
}
  1. 用的时候给私有字段加两个特性就搞定:
public class TestScript : MonoBehaviour
{
    [SerializeField, ReadOnly]
    private int _privateReadOnlyValue = 10;
}

方法2:自定义Editor脚本(灵活可控)

如果需要更复杂的逻辑(比如只在运行时只读,编辑时可改),可以写自定义Editor:

  1. 先给脚本里的私有字段加上[SerializeField]:
public class TestScript : MonoBehaviour
{
    [SerializeField]
    private int _privateReadOnlyValue = 10;
}
  1. 在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,提问作者나만없어 고양이

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:12:42