Skip to content

5. Serializable Types

Miłosz Matkowski edited this page Nov 30, 2024 · 4 revisions

SerializedType

Allows to serialize System.Type and pick it through a dedicated picker.

[TypeConstraint(typeof(Collider), AllowAbstract = false, AllowObsolete = false, TypeSettings = TypeSettings.Class, TypeGrouping = TypeGrouping.None)]
public SerializedType serializedType;

public void Usage()
{
	var type = serializedType.Type;
}

inspector

SerializedScene

Allows to serialize SceneAssets and use them in Runtime.

public SerializedScene serializedScene;

public void Usage()
{
	UnityEngine.SceneManagement.SceneManager.LoadScene(serializedScene.BuildIndex);
}

inspector

[SceneDetails]
public SerializedScene serializedScene;

inspector

Keep in mind that SerializedScene stores Scene's index, name, and path. These properties are updated each time scenes collection in the Build Settings is updated or any SceneAsset is created/removed/reimported. Unfortunately, you need to handle associated objects' reserialization by yourself, otherwise, e.g. updated indexes won't be saved. I prepared for you a static event SceneSerializationUtility.OnCacheRefreshed that can be used to validate SerializedScenes in your project. You can link SerializedScene in a ScriptableObject and trigger reserialization (EditorUtility.SetDirty()) if needed, it's really convenient approach.

SerializedDictionary<TK, TV>

Allows to serialize and use Dictionaries. The presented class implements the IDictionary interface, so it can be easily used like the standard version.

Requires at least Unity 2020.1.x because of generic serialization and has to be assigned in the Settings file.

inspector

#if UNITY_2020_1_OR_NEWER
public SerializedDictionary<int, GameObject> serializedDictionary;

public void Usage()
{
	serializedDictionary.Add(3, new GameObject("TestObject"));
	serializedDictionary.ContainsKey(2);
	//etc. like the standard System.Collections.Generic.Dictionary<>
	System.Collections.Generic.Dictionary<int, GameObject> dictionary = serializedDictionary;
}
#endif

inspector

inspector

SerializedDateTime

Allows to serialize DateTime.

public SerializedDateTime serializedDateTime;

public void Usage()
{
	System.DateTime dateTime = serializedDateTime;
}

inspector

SerializedDirectory

Allows to serialize folders in a form of assets and retrieve direct paths in runtime.

public SerializedDirectory serializedDirectory;

public void Usage()
{
	var path = serializedDirectory.DirectoryPath;
}

inspector