Files
FlaxEngine/Source/Engine/Content/JsonAsset.cs
2022-04-13 21:18:35 +02:00

65 lines
1.9 KiB
C#

// Copyright (c) 2012-2022 Wojciech Figat. All rights reserved.
using System;
using FlaxEngine.Json;
namespace FlaxEngine
{
partial class JsonAsset
{
private object _instance;
/// <summary>
/// Gets the instance of the serialized object from the json asset data. Cached internally.
/// </summary>
public object Instance => _instance ?? (_instance = CreateInstance());
/// <summary>
/// Creates a new instance of the serialized object from the json asset data.
/// </summary>
/// <remarks>Use <see cref="Instance"/> to get cached object.</remarks>
/// <returns>The new object or null if failed.</returns>
public T CreateInstance<T>()
{
return (T)CreateInstance();
}
/// <summary>
/// Creates a new instance of the serialized object from the json asset data.
/// </summary>
/// <remarks>Use <see cref="Instance"/> to get cached object.</remarks>
/// <returns>The new object or null if failed.</returns>
public object CreateInstance()
{
if (WaitForLoaded())
return null;
object obj = null;
var dataTypeName = DataTypeName;
var type = Type.GetType(dataTypeName);
if (type != null)
{
try
{
// Create instance
obj = Activator.CreateInstance(type);
// Deserialize object
var data = Data;
JsonSerializer.Deserialize(obj, data);
}
catch (Exception ex)
{
Debug.LogException(ex, this);
}
}
else
{
Debug.LogError(string.Format("Missing type '{0}' to create Json Asset instance.", dataTypeName), this);
}
return obj;
}
}
}