【Attribute】Inspector视图可视不可编辑字段特性

简介

在Unity开发中,有时候我们存在这种需求,需要在Inspector视图中可以查看字段信息但是无法对字段进行赋值,那么我们也可以像Unity内置的[SerializeField]、[Tooltip]等特性那样自定义一个特性,用于满足这个需求。

代码示例(C#)

cs 复制代码
#if UNITY_EDITOR
using System;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

// 禁用可序列化字段在Inspector面板的编辑
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class EditDisabledAttribute : PropertyAttribute { }

// EditDisabledAttribute的自定义绘制器
[CustomPropertyDrawer(typeof(EditDisabledAttribute))]
class EditDisabledDrawer : PropertyDrawer
{
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return EditorGUI.GetPropertyHeight(property, label, true);
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (IsArray() || IsList())
        {
            EditorGUI.BeginDisabledGroup(true);
            EditorGUI.PropertyField(position, property, label, true);
            EditorGUI.EndDisabledGroup();
        }
        else
        {
            GUI.enabled = false;
            EditorGUI.PropertyField(position, property, label, true);
            GUI.enabled = true;
        }
    }

    // 是否为数组
    private bool IsArray()
    {
        return fieldInfo.FieldType.IsArray;
    }

    // 是否为列表
    private bool IsList()
    {
        return fieldInfo.FieldType.IsGenericType && fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(List<>);
    }
}
#endif

效果截图

如果这篇文章对你有帮助,请给作者点个赞吧

相关推荐
红黑色的圣西罗14 小时前
Unity减少Draw和SetPassCall的手段简述
unity·游戏引擎
淡海水15 小时前
【节点】[CorneaRefraction节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·cornea·refraction
小贺儿开发15 小时前
《唐朝诡事录之西行》——降魔变
科技·unity·人机交互·创意·文旅·hdrp
郁闷的网纹蟒15 小时前
虚幻5---第15部分---宝藏(掉落物)
开发语言·c++·ue5·游戏引擎·虚幻
泡泡茶壶ᐇ16 小时前
Unity游戏开发入门指南:从零开始理解游戏引擎核心概念(二:Unity游戏开发的本质:从可视化编程到面向对象的顿悟)
unity·游戏引擎
小贺儿开发16 小时前
Unity3D 汽车视界(轻量版)
科技·unity·汽车·人机交互·可视化·urp
在路上看风景2 天前
32. 代码优化
unity
在路上看风景2 天前
01. 编辑器外观
unity
CreasyChan2 天前
unity C# 实现屏蔽敏感词
unity·c#·游戏引擎
玉梅小洋2 天前
Unity 2D游戏开发 Ruby‘s Adventure 2:主角和第一脚本
游戏·unity·游戏引擎·游戏程序·ruby·游戏开发