Unity编辑器窗口List添加元素失败:如何填充随机字符串?
问题解决方法
你的代码存在两个问题:一是直接修改strings列表后未同步Unity编辑器的序列化状态,导致界面显示为空;二是当前生成的是随机数字字符串,而非你需要的随机字母字符串。以下是两种解决方式:
方式一:手动同步序列化状态
直接修改列表后,调用SerializedObject.Update()同步状态,让编辑器感知到列表变化:
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class EditorWindowTester : EditorWindow { private static readonly Vector2Int size = new Vector2Int(500, 500); public List<string> strings = new List<string>(); private SerializedObject so; private SerializedProperty stringsProp; [MenuItem("Editor Test/Strings")] public static void Init() { EditorWindow window = GetWindow<EditorWindowTester>(); window.minSize = size; window.maxSize = size; } private void OnGUI() { EditorGUILayout.PropertyField(stringsProp, true); so.ApplyModifiedProperties(); } private void OnEnable() { so = new SerializedObject(this); stringsProp = so.FindProperty("strings"); // 清空列表,避免重复打开窗口时元素累加 strings.Clear(); for (int i = 0; i < 10; i++) { // 生成随机小写字母(a-z) char randomLetter = (char)Random.Range('a', 'z' + 1); strings.Add(randomLetter.ToString()); } // 同步序列化对象状态,让SerializedProperty获取最新列表 so.Update(); } }
方式二:直接操作SerializedProperty(推荐)
Unity编辑器序列化更推荐通过SerializedProperty直接修改列表,无需手动同步状态,更符合编辑器工作流:
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class EditorWindowTester : EditorWindow { private static readonly Vector2Int size = new Vector2Int(500, 500); public List<string> strings = new List<string>(); private SerializedObject so; private SerializedProperty stringsProp; [MenuItem("Editor Test/Strings")] public static void Init() { EditorWindow window = GetWindow<EditorWindowTester>(); window.minSize = size; window.maxSize = size; } private void OnGUI() { EditorGUILayout.PropertyField(stringsProp, true); so.ApplyModifiedProperties(); } private void OnEnable() { so = new SerializedObject(this); stringsProp = so.FindProperty("strings"); // 清空原有数组元素 stringsProp.ClearArray(); for (int i = 0; i < 10; i++) { // 插入新的数组元素 stringsProp.InsertArrayElementAtIndex(i); SerializedProperty element = stringsProp.GetArrayElementAtIndex(i); // 设置随机字母字符串 char randomLetter = (char)Random.Range('a', 'z' + 1); element.stringValue = randomLetter.ToString(); } // 应用修改到序列化对象 so.ApplyModifiedProperties(); } }
额外说明
- 两种方式都添加了列表清空逻辑,避免多次打开窗口时元素重复累加。
- 随机字母生成逻辑采用
Random.Range('a', 'z' + 1),因为Random.Range的上限是排他的,所以要加1才能包含'z'。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

