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

Unity中如何用OdinInspector实现列表元素多选以批量编辑?

在Unity中用OdinInspector实现列表多选与批量编辑

你的代码没生效的核心原因是没开启列表的多选模式,且缺少对应选中状态的处理逻辑。以下是完整的实现方案:

关键配置与代码示例

1. 基础元素类示例

假设你的BaseAreaGUI包含需要批量编辑的属性:

public class BaseAreaGUI
{
    public string name;
    public float size;
    public Color color;
}

2. 带多选与批量编辑的管理器代码

using Sirenix.OdinInspector;
using UnityEngine;
using System.Collections.Generic;

public class AreaManager : MonoBehaviour
{
    [PropertyOrder(2)]
    [PropertySpace(10)]
    // 核心:开启多选模式,配置列表显示规则
    [ListDrawerSettings(
        DraggableItems = false,
        ListElementLabelName = "name",
        HideAddButton = true,
        HideRemoveButton = true,
        SelectionMode = ListSelectionMode.Multiple // 必须设置这个才会启用多选
    )]
    [ShowInInspector]
    // 绑定选中状态变更的回调方法
    [ListItemSelector("OnListItemSelected")]
    public List<BaseAreaGUI> baseAreas = new List<BaseAreaGUI>();

    // 存储选中元素的索引,用于后续批量操作
    private List<int> selectedIndices = new List<int>();

    // Odin要求的回调方法签名:接收索引和选中状态
    private void OnListItemSelected(int index, bool isSelected)
    {
        if (isSelected)
        {
            if (!selectedIndices.Contains(index)) selectedIndices.Add(index);
        }
        else
        {
            selectedIndices.Remove(index);
        }
    }

    // 批量修改示例1:设置选中元素的Size为2
    [Button("批量设置Size为2")]
    private void BatchSetSize()
    {
        foreach (int index in selectedIndices)
        {
            if (index >= 0 && index < baseAreas.Count)
            {
                baseAreas[index].size = 2f;
            }
        }
        UnityEditor.EditorUtility.SetDirty(this); // 标记对象为脏,确保修改能保存
    }

    // 批量修改示例2:设置选中元素的颜色为红色
    [Button("批量设置颜色为红色")]
    private void BatchSetColor()
    {
        foreach (int index in selectedIndices)
        {
            if (index >= 0 && index < baseAreas.Count)
            {
                baseAreas[index].color = Color.red;
            }
        }
        UnityEditor.EditorUtility.SetDirty(this);
    }
}

核心说明

  • 开启多选模式:在ListDrawerSettings中添加SelectionMode = ListSelectionMode.Multiple是启用多选的关键,之前的代码缺失了这个配置。
  • 选中状态回调:ListItemSelector绑定的方法必须符合void 方法名(int index, bool isSelected)的签名,用来维护选中元素的索引列表。
  • 批量操作实现:通过维护的选中索引列表,遍历修改对应元素的属性即可完成批量编辑,搭配[Button]属性可以快速在Inspector中触发操作。
  • 多选操作方式:在Inspector中按住Ctrl点击可多选单个元素,按住Shift可连续选择一段元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:43:26