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

Unity Inspector新增List项时自动同步主脚本字符串长度的实现咨询

问题解答

没错,你必须编写自定义编辑器脚本才能实现这个需求。Unity默认的Inspector没有这种自动关联字段赋值的逻辑,要实现通过Inspector新增列表项时自动设置stringLength的功能,就得靠自定义Editor来拦截列表添加操作并赋值。

实现方案

  1. 先修正原脚本的语法错误(原代码里构造函数和Add方法的写法存在问题)
  2. 编写自定义编辑器脚本,监听列表的长度变化,在新增项时自动赋值

修正后的原脚本

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Snippet
{
    public int stringLength = 0;
}

public class MainScript : MonoBehaviour
{
    public string theText;
    public List<Snippet> snippets = new List<Snippet>();
}

自定义编辑器脚本(需放在Editor文件夹下)

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(MainScript))]
public class MainScriptEditor : Editor
{
    private SerializedProperty _theText;
    private SerializedProperty _snippets;

    private void OnEnable()
    {
        // 获取序列化的字段引用
        _theText = serializedObject.FindProperty("theText");
        _snippets = serializedObject.FindProperty("snippets");
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // 绘制文本输入框
        EditorGUILayout.PropertyField(_theText);

        // 记录列表修改前的长度
        int oldCount = _snippets.arraySize;

        // 绘制Snippets列表(true参数表示展开显示所有元素)
        EditorGUILayout.PropertyField(_snippets, true);

        // 检查是否新增了列表项
        if (_snippets.arraySize > oldCount)
        {
            // 获取刚新增的Snippet项
            var newItem = _snippets.GetArrayElementAtIndex(_snippets.arraySize - 1);
            // 给新项的stringLength赋值为theText的当前长度
            newItem.FindPropertyRelative("stringLength").intValue = _theText.stringValue.Length;
        }

        serializedObject.ApplyModifiedProperties();
    }
}

额外说明

  • 这个脚本会在你点击Inspector里Snippets列表的"+"按钮时,自动把新项的stringLength设为当前theText的字符串长度
  • 编辑器脚本必须放在名为Editor的文件夹中,否则Unity无法识别它
  • 如果需要在修改theText时同步更新所有已有Snippet的stringLength,可以在_theText的数值变化时遍历列表批量修改

内容的提问来源于stack exchange,提问作者Mike The Elf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 23:48:22