Сериализация пользовательского списка классов Unity с типом EnumC#

Место общения программистов C#
Ответить
Anonymous
 Сериализация пользовательского списка классов Unity с типом Enum

Сообщение Anonymous »

Я пытаюсь сериализовать список пользовательского класса в инспекторе Unity. Этот класс содержит перечисляемый тип PlayerOptionType. Однако всякий раз, когда я пытаюсь добавить экземпляр этого в список в инспекторе, список исчезает из инспектора, и консоль постоянно выводит следующую ошибку.
Изображение

Мой код ниже:
Базовый класс

Код: Выделить всё

using UnityEngine;

public class Base : MonoBehaviour // A base class that all items, maptiles and objects inherit from
{
[SerializeField]
internal ObjectType objectType;

public ObjectType ObjType { get { return objectType; } }
}
Класс ItemBase

Код: Выделить всё

using System.Collections.Generic;
using UnityEngine;

public class ItemBase : Base // A item base class that all game items inherit from
{
[SerializeField, Header("Item Base Options")]
internal bool interatable;
[SerializeField]
internal List
 interactions; // The List of the custom class I want to serialize
[SerializeField]
internal bool isTileBlocker;
[SerializeField]
private float fadeTime;

[SerializeField, Header("Misc Properties")]
internal bool isVisible;

internal MeshRenderer meshRenderer;

public bool IsTileBlocker { get { return isTileBlocker; } }

public virtual void InitaliseItem()
{
isVisible = false;
meshRenderer = GetComponent();
meshRenderer.enabled = false;
}

public virtual void SetVisible(bool visible)
{
isVisible = visible;
meshRenderer.enabled = visible;
}
}
Класс PlayerOption

Код: Выделить всё

using System;
using UnityEngine;

[Serializable]
public class PlayerOption // The custom class I want to serialize, stores data of a game object and what type of action a player can make with it
{
[SerializeField]
private string description;
[SerializeField]
private PlayerOptionType type;
[SerializeField]
private GameObject target;

public string Description { get { return description; } }
public PlayerOptionType Type { get { return type; } }
public GameObject Target { get { return target; } }

public PlayerOption(PlayerOptionType type, GameObject target, string description)
{
this.description = description;
this.type = type;
this.target = target;
}
}
У меня есть другие области моего проекта, в которых есть сериализованные перечисления, которые отображаются в окне проверки. Однако добавление их в сериализуемый класс создает эту проблему. Иногда Unity работает временно, позволяя мне добавлять или удалять один или два экземпляра из списка, а затем снова начинает выдавать эту ошибку.
Я пробовал сделать поля общедоступными, добавив новое пустое конструктор класса, устанавливая значение по умолчанию для перечисления и добавляя тег [serializable] к определению перечисления, среди прочего. Кажется, ни один из них вообще не решил проблему.
Изменить:
Добавление дополнительных разъяснений PlayerOptionType — это перечисление, которое, как мне кажется, причина проблемы и выглядит следующим образом

Код: Выделить всё

public enum PlayerOptionType
{
Null,
Player_Attack,
Player_Interact,
Player_Move
}
Добавление полной ошибки в сообщение выглядит следующим образом
Изображение

Редактировать 2:
После рассмотрения первой выданной ошибки кажется, что она отличается от всех следующих ошибок.

Код: Выделить всё

NullReferenceException:  SerializedObject of SerializedProperty has been Disposed.
UnityEditor.SerializedProperty.get_intValue () (at :0)
UnityEditor.UIElements.Bindings.ListViewSerializedObjectBinding.UnbindListViewItem (UnityEngine.UIElements.VisualElement ve, System.Int32 index) (at :0)
UnityEngine.UIElements.ListViewController.UnbindItem (UnityEngine.UIElements.VisualElement element, System.Int32 index) (at :0)
UnityEngine.UIElements.CollectionViewController.InvokeUnbindItem (UnityEngine.UIElements.ReusableCollectionItem reusableItem, System.Int32 index) (at :0)
UnityEngine.UIElements.VerticalVirtualizationController`1[T].ReleaseItem (System.Int32 activeItemsIndex) (at :0)
UnityEngine.UIElements.DynamicHeightVirtualizationController`1[T].ReleaseItem (System.Int32 activeItemsIndex) (at :0)
UnityEngine.UIElements.VerticalVirtualizationController`1[T].Refresh (System.Boolean rebuild) (at :0)
UnityEngine.UIElements.DynamicHeightVirtualizationController`1[T].Refresh (System.Boolean rebuild) (at :0)
UnityEngine.UIElements.BaseVerticalCollectionView.RefreshItems () (at :0)
UnityEngine.UIElements.CollectionViewController.set_itemsSource (System.Collections.IList value) (at :0)
UnityEngine.UIElements.BaseVerticalCollectionView.set_itemsSource (System.Collections.IList value) (at :0)
UnityEditor.UIElements.Bindings.ListViewSerializedObjectBinding.ClearListView () (at :0)
UnityEditor.UIElements.Bindings.ListViewSerializedObjectBinding.Release () (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.RemoveBinding (UnityEngine.UIElements.IBindable bindable, System.Boolean forceRemove) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.Unbind (UnityEngine.UIElements.VisualElement element) (at :0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation.UnbindTree (UnityEngine.UIElements.VisualElement element) (at :0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation.Unbind (UnityEngine.UIElements.VisualElement element) (at :0)
UnityEditor.UIElements.BindingExtensions.Unbind (UnityEngine.UIElements.VisualElement element) (at :0)
UnityEditor.UIElements.PropertyField.Reset (UnityEditor.SerializedProperty newProperty) (at :0)
UnityEditor.UIElements.PropertyField.Reset (UnityEditor.UIElements.SerializedPropertyBindEvent evt) (at :0)
UnityEditor.UIElements.PropertyField.ExecuteDefaultActionAtTarget (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEngine.UIElements.CallbackEventHandler.HandleEvent (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEngine.UIElements.CallbackEventHandler.HandleEventAtCurrentTargetAndPhase (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEngine.UIElements.CallbackEventHandler.HandleEventAtTargetPhase (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEngine.UIElements.CallbackEventHandler.HandleEventAtTargetAndDefaultPhase (UnityEngine.UIElements.EventBase evt) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.SendBindingEvent[TEventType] (TEventType evt, UnityEngine.UIElements.VisualElement target) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element,  UnityEditor.SerializedProperty parentProperty) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at :0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.Bind (UnityEngine.UIElements.VisualElement element) (at :0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation.Bind (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedObject obj) (at :0)
UnityEditor.UIElements.BindingExtensions.Bind (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedObject obj) (at :0)
UnityEditor.UIElements.InspectorElement.SetEditor (UnityEditor.Editor value) (at :0)
UnityEditor.UIElements.EditorElement.Reinit (System.Int32 editorIndex) (at :0)
UnityEditor.PropertyEditor.ProcessEditorElementsToRebuild (UnityEditor.Editor[] editors) (at :0)
UnityEditor.PropertyEditor.DrawEditors (UnityEditor.Editor[] editors) (at :0)
UnityEditor.PropertyEditor.RebuildContentsContainers () (at :0)
UnityEditor.InspectorWindow.RedrawFromNative () (at :0)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions()
При необходимости я могу предоставить дополнительную информацию в дальнейших изменениях.

Подробнее здесь: https://stackoverflow.com/questions/790 ... -enum-type
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»