defmodule Manganese.SerializationKit.Structs.UnityComponent do @moduledoc """ A generic Unity component. There are other modules for specific component types. When de/serializing with the generic `Manganese.SerializationKit.Structs.UnityComponent` module, the `:type` property will be inspected and the appropriate de/serializer will be used. If the component type is not known, it will use this module as a struct. The known component types are: - `Manganese.SerializationKit.Structs.UnityTransformComponent` - `Manganese.SerializationKit.Structs.UnityBoxColliderComponent` # Deserialization - *See `from_map/1`* # Serialization - *See `to_map/1`* """ alias Manganese.SerializationKit.Structs alias Manganese.SerializationKit.Enumerations @typedoc """ The internal ID used by Unity to uniquely identify components. """ @type id :: pos_integer @typedoc """ A Unity component of an unknown type. """ @type t :: %Structs.UnityComponent{ id: id, type: Enumerations.UnityComponentType.t } @enforce_keys [ :id ] defstruct [ :id, :type ] # Deserialization @doc """ Deserialize a component from a map. Note this deserialization method may return a struct of a component type-specific module. """ @spec from_map(t_external) :: term def from_map(%{ "id" => id, "type" => type } = params) do type = Enumerations.UnityComponentType.from_integer type case type do :transform -> Structs.UnityTransformComponent.from_map params :box_collider -> Structs.UnityBoxColliderComponent.from_map params _ -> %Structs.UnityComponent{ id: id, type: type } end end # Serialization @type t_external :: map @doc """ Serialize a component to a map. If a component struct of a component type-specific class is given, the appropriate serializer will be used. """ @spec to_map(term) :: t_external def to_map(%Structs.UnityComponent{ id: id, type: type }) do %{ "id" => id, "type" => Enumerations.UnityComponentType.to_integer(type) } end def to_map(unity_component) do case unity_component.type do :transform -> Structs.UnityTransformComponent.to_map unity_component :box_collider -> Structs.UnityBoxColliderComponent.to_map unity_component end end end