Serializable

切换到手册

描述

指示可序列化的类或结构。

要启用序列化,则应用 [Serializable] 属性。有关序列化的更多信息,请参阅脚本序列化

注意:只能序列化非抽象、非泛型自定义类。

在以下示例中,我们创建了一个自定义播放器结构,并为其赋予 [Serializable] 属性,以使其可序列化。然后,我们创建了一个播放器类型的私有字段,并对其应用 [SerializeField] 属性,以使其显示在检查器中。

using System;
using UnityEngine;

public class Player : MonoBehaviour { //Create a custom struct and apply [Serializable] attribute to it [Serializable] public struct PlayerStats { public int movementSpeed; public int hitPoints; public bool hasHealthPotion; }

//Make the private field of our PlayerStats struct visible in the Inspector //by applying [SerializeField] attribute to it [SerializeField] private PlayerStats stats; }