Question by
kayraucklnc · Jun 26, 2021 at 05:06 PM ·
listcustom editorserializedpropertycasting
How to cast SerializedProperty back to custom class?
I have a list of modelAsset in type of SerializedProperty and I want to cast them back to modelAsset.
ModelAsset.cs
----------------------
[Serializable]
public struct modelAsset {
public string modelName;
public GameObject Prefab;
public List<GameObject> up;
public List<GameObject> down;
public List<GameObject> back;
public List<GameObject> forward;
public List<GameObject> right;
public List<GameObject> left;
}
I want to take the first item in the list and cast it back to its original class but unity says The as operator must be used with a reference type or nullable type (''modelAsset" is a non-nullable type) to me
modelAsset modelAss = list.serializedProperty.GetArrayElementAtIndex(0).objectReferenceValue as System.Object as modelAsset;
What I currently can do is:
listItem.FindPropertyRelative("up").GetArrayElementAtIndex(0).objectReferenceValue as GameObject);
Which can return the first GameObject from its "up" named List.
Comment
A struct
can't be nulled because it's a value type, and not a reference type.
The as
operator converts the result of an expression to a given reference or nullable value type.
Have you tried the standard way to cast instead?
modelAsset modelAss = (modelAsset) list.serializedProperty.GetArrayElementAtIndex(0).objectReferenceValue;
This is when I try your method
And this when I try to make it a class instead of struct
image-2021-06-28-113216.png
(7.4 kB)
image-2021-06-28-113241.png
(36.3 kB)