【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

效果截图

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

相关推荐
AI视觉网奇4 小时前
虚幻引擎 metahuman
游戏引擎·虚幻
技术探讨者9 小时前
Unity 框架:从核心构成到实践应用的全面解析
unity·游戏引擎
牛掰是怎么形成的9 小时前
Unity Legacy动画与骨骼动画的本质区别
unity·游戏引擎
weixin_458360919 小时前
Unity使用Cursor Editor
unity
萘柰奈9 小时前
Unity学习--2D动画--[序列帧动画]2D序列帧动画
学习·unity·游戏引擎
EQ-雪梨蛋花汤9 小时前
【Unity笔记】Unity 模型渲染优化:从 Batching 到 GI 设置的完整指南
笔记·unity·游戏引擎
花花_19 小时前
一步封神:Unity环境搭建终极全宇宙级攻略(Win/Mac/云)
macos·unity·游戏引擎
Unity打怪升级9 小时前
【Unity精品源码】Ultimate Character Controller:高级角色控制器完整解决方案
游戏·unity·ue5·游戏引擎·godot·游戏程序·cocos2d
qq_312982139 小时前
Unity国际版下载方法 https://unity.com/releases 被重定向问题导致下载不到Unity国际版的问题解决
unity·游戏引擎