Skip to content

Instantly share code, notes, and snippets.

@s2kw
Last active October 23, 2024 09:13
Show Gist options
  • Save s2kw/d1cab0732670c85d1f40b36db8caa661 to your computer and use it in GitHub Desktop.
Save s2kw/d1cab0732670c85d1f40b36db8caa661 to your computer and use it in GitHub Desktop.
UnityでEnumをSerialize対象とした場合の注意

Unity で SerializeField をつかった Serialize はよく行うが注意点がある。 Serialize された時に Int になっているということ。そしてその Serialize された Int は順番は保存しているが直接的なデータは保存されていないということ。

例えばこんな enum を用意する。

public enum SampleEnum  
{  
    Zero,  
    One,  
    Two,  
    Three,  
}

そしてこんなフィールドを用意する。

[SerializeField]
private List<SampleEnum> _sampleEnums = new();

するとこんな感じで Inspector から Serialize できるようになる。 ![[../../attachments/EnumSerialize.png]]

ここまではいい。 Enum の列挙型の順番を変更する。今回は単純な削除にしてみる。

public enum SampleEnum  
{  
//    Zero,  
    One,  
    Two,  
    Three,  
}

するとこんな感じで Inspector では指定している値が変わってしまうことになる。 ![[../../attachments/EnumSerializeRemoved.png]]

この時点で git に diff は出ない。内部的にも状態が変わっているわけではないということ。 未定義の 3 に該当する値は存在しないがエラー等は出ずに空欄と同じ扱いになっている。

つまり、コードから書き換えたり順番を入れ替えたりした場合に、このデータがどこぞで Serialize していたとしても変更に気付けないということ。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment