【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

效果截图

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

相关推荐
小小数媒成员1 小时前
Unity的包含文件
unity·游戏引擎
mxwin3 小时前
Unity Shader 实战屏幕颜色抓取实现径向模糊 (URP)
unity·游戏引擎·shader·uv
林枫依依7 小时前
Unity2017 项目源码打开即崩溃,无法打开的解决办法
unity
wearegogog1237 小时前
ESP32迷你无人机开发代码详解
游戏引擎·无人机·cocos2d
心前阳光9 小时前
Unity使用豆包语音模型
unity·游戏引擎
张老师带你学9 小时前
unity资源:星际飞船 陨石 虫族 星球
科技·游戏·unity·模型·游戏美术
心前阳光9 小时前
Unity使用豆包语言模型
unity·语言模型
魔士于安9 小时前
unity宇宙飞船
游戏·unity·游戏引擎·贴图·模型
RReality9 小时前
【Unity Shader】高级光照与阴影总结:渲染路径、多光源、透明阴影
unity·游戏引擎
浪客川9 小时前
godot-rust入门案例
rust·游戏引擎·godot