Current section

Files

Jump to
manganese_serialization_kit lib structs assets unity_asset.ex
Raw

lib/structs/assets/unity_asset.ex

defmodule Manganese.SerializationKit.Structs.UnityAsset do
@moduledoc """
A generic Unity asset. Assets are usually associated with an asset bundle.
There are other modules for specific asset types. When de/serializing with the generic `Manganese.SerializationKit.Structs.UnityAsset` module, the `:type` property will be inspected and the appropriate de/serializer will be used. If the asset type is not known, it will use this module as a struct.
The known asset types are:
- `Manganese.SerializationKit.Structs.UnityTextAsset`
- `Manganese.SerializationKit.Structs.UnityPrefabAsset`
- `Manganese.SerializationKit.Structs.UnityMaterialAsset`
# 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 assets.
"""
@type id :: pos_integer
@typedoc """
A Unity asset of an unknown type.
"""
@type t :: %Structs.UnityAsset{
path: String.t,
id: id,
name: String.t,
type: Enumerations.UnityAssetType.t
}
@enforce_keys [
:path,
:id,
:name
]
defstruct [
:path,
:id,
:name,
:type
]
# Deserialization
@doc """
Deserialize an asset from a map.
Note this deserialization method may return a struct of an asset type-specific module.
"""
@spec from_map(t_external) :: t
def from_map(%{
"path" => path,
"id" => id,
"name" => name,
"type" => type
} = params) do
case Enumerations.UnityAssetType.from_integer type do
:text -> Structs.UnityTextAsset.from_map params
:prefab -> Structs.UnityPrefabAsset.from_map params
:material -> Structs.UnityMaterialAsset.from_map params
_ ->
%Structs.UnityAsset{
path: path,
id: id,
type: Enumerations.UnityAssetType.from_integer(type),
name: name
}
end
end
# Serialization
@type t_external :: map
@doc """
Serialize an asset to a map.
If a asset struct of an asset type-specific class is given, the appropriate serializer will be used.
"""
@spec to_map(term) :: t_external
def to_map(asset) do
case asset.type do
:text -> Structs.UnityTextAsset.to_map asset
:prefab -> Structs.UnityPrefabAsset.to_map asset
:material -> Structs.UnityMaterialAsset.to_map asset
_ ->
%Structs.UnityAsset{
path: path,
id: id,
type: type,
name: name
} = asset
%{
"path" => path,
"id" => id,
"name" => name,
"type" => Enumerations.UnityAssetType.to_integer(type)
}
end
end
end