Version: 2023.1

SerializedProperty.DeleteArrayElementAtIndex

切换到手册
public void DeleteArrayElementAtIndex (int index);

描述

删除数组中指定索引处的元素。

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class DeleteArrayElementAtIndexExample : ScriptableObject { public List<string> m_Data;

[MenuItem("Example/SerializedProperty/DeleteArrayElementAtIndex Example")] static void MenuCallback() { DeleteArrayElementAtIndexExample obj = ScriptableObject.CreateInstance<DeleteArrayElementAtIndexExample>(); obj.m_Data = new List<string>() { "The", "big", "cat", "jumped." };

SerializedObject serializedObject = new SerializedObject(obj); SerializedProperty arrayProperty = serializedObject.FindProperty("m_Data");

arrayProperty.DeleteArrayElementAtIndex(1);

// With previous deletion index 2 now becomes the last element arrayProperty.DeleteArrayElementAtIndex(2);

serializedObject.ApplyModifiedProperties();

// Outputs "The cat" Debug.Log("Final array contents: " + string.Join(" ", obj.m_Data)); } }
using UnityEngine;
using UnityEditor;

public class DeleteArrayElementAtIndexExample2 : ScriptableObject { public int[] m_Array = new int[] { 1, -1, -1, 3, -1, -1, 1, 3, -1 };

[MenuItem("Example/SerializedProperty/DeleteArrayElementAtIndex Example 2")] static void MenuCallback() { var scriptableObject = ScriptableObject.CreateInstance<DeleteArrayElementAtIndexExample2>();

using (var serializedObject = new SerializedObject(scriptableObject)) { SerializedProperty arrayProperty = serializedObject.FindProperty("m_Array");

// Iterate the array removing any negative numbers int arraySize = arrayProperty.arraySize; for (int index = 0; index < arraySize;) { var arrayElement = arrayProperty.GetArrayElementAtIndex(index); if (arrayElement.intValue < 0) { arrayProperty.DeleteArrayElementAtIndex(index); arraySize--; } else { index++; } }

serializedObject.ApplyModifiedProperties(); Debug.Log("Cleaned array contents: " + string.Join(" ", scriptableObject.m_Array)); } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961