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

如何在Unity Inspector中显示只读变量并置灰不可编辑?

解决Unity Inspector中变量置灰不可编辑的问题

要让itemType变量在Inspector中呈现置灰状态且无法修改,可通过自定义ReadOnly属性及对应编辑器抽屉类实现,具体步骤如下:

1. 创建ReadOnly属性脚本

在项目中新建C#脚本ReadOnlyAttribute.cs,代码如下:

using UnityEngine;

public class ReadOnlyAttribute : PropertyAttribute { }

2. 实现编辑器抽屉类

在项目的Editor目录下新建C#脚本ReadOnlyDrawer.cs,代码如下:

using UnityEditor;
using UnityEngine;

[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // 禁用编辑功能
        GUI.enabled = false;
        // 绘制原有属性字段
        EditorGUI.PropertyField(position, property, label, true);
        // 恢复GUI编辑状态
        GUI.enabled = true;
    }
}

3. 修改目标脚本

给itemType变量添加[ReadOnly]属性:

using System;
using UnityEngine;

[CreateAssetMenu(fileName = "Weapon",  menuName = "Item/Weapon")]
public class WeaponItemSprite : ItemTypeScriptableObject
{
    public GameObject gameObject;
    public Sprite sprite;
    public string weaponName = "Weapon name";
    public Rarity rarity = Rarity.Normal;
    // 添加ReadOnly属性实现置灰不可编辑
    [ReadOnly]
    public ItemType itemType = ItemType.Weapon;
    [Range(0f, 1000f)]
    public float damage = 1f;
    [Range(0f, 20f)]
    public int cost = 1;
}

效果展示

修改完成后,Inspector中的itemType字段会变为置灰状态,无法被编辑,效果如下:
Inspector界面截图


内容的提问来源于stack exchange,提问作者serjeq_unity

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:07:40