Skip to content

Instantly share code, notes, and snippets.

@DenchiSoft
Last active December 16, 2019 22:33
Show Gist options
  • Select an option

  • Save DenchiSoft/9d0c48feb5cd1dbcb3164a5c8c71befe to your computer and use it in GitHub Desktop.

Select an option

Save DenchiSoft/9d0c48feb5cd1dbcb3164a5c8c71befe to your computer and use it in GitHub Desktop.
Runtime-Loading external Live2D Cubism Models on Android
using Live2D.Cubism.Core;
using Live2D.Cubism.Framework.Json;
using System;
using System.IO;
using System.Text;
using UnityEngine;
public static class ExternalCubismModelLoader
{
/// <summary>
/// Instantiates and returns a Live2D model and puts it into the scene on
/// a new GameObject (no parent).
/// This works at runtime and will read models on Android from a path like:
/// \Galaxy S10+\Phone\Android\data\com.test.myappname\files\modelPath
/// </summary>
/// <param name="modelPath">Path relative to app persistentDataPath-folder.</param>
/// <returns>The instantiated Live2D model component.</returns>
public static CubismModel LoadCubismModelFromModel3Json(string modelPath)
{
string absolutePath = Path.Combine(Application.persistentDataPath, modelPath);
try
{
CubismModel3Json ModelJson = CubismModel3Json.LoadAtPath(absolutePath, CubismLoadAssetExternal);
return ModelJson.ToModel();
}
catch (Exception)
{
// Usually caused by wrong path/filename or invalid/broken model files.
Debug.LogError("Error loading model: " + absolutePath);
}
return null;
}
/// <summary>
/// Loads asset from external folder.
/// Used as delegate (LoadAssetAtPathHandler) for CubismModel3Json.LoadAtPath(..)
/// </summary>
/// <param name="assetType">Asset type.</param>
/// <param name="absolutePath">Path to asset.</param>
/// <returns>The asset on success, null otherwise.</returns>
public static object CubismLoadAssetExternal(Type assetType, string absolutePath)
{
if (File.Exists(absolutePath))
{
byte[] bytes = File.ReadAllBytes(absolutePath);
if (assetType == typeof(byte[]))
{
return bytes;
}
else if (assetType == typeof(string))
{
return Encoding.ASCII.GetString(bytes);
}
else if (assetType == typeof(Texture2D))
{
var texture = new Texture2D(1, 1);
texture.LoadImage(bytes);
return texture;
}
throw new NotSupportedException();
}
else
{
throw new FileNotFoundException();
}
}
}
using Live2D.Cubism.Core;
using Live2D.Cubism.Rendering;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
CubismModel model = ExternalCubismModelLoader.LoadCubismModelFromModel3Json("Live2DModels/Koharu/Koharu.model3.json");
if (model != null)
{
model.transform.position = new Vector3(0, 0, 1);
model.GetComponent<CubismRenderController>().SortingMode = CubismSortingMode.BackToFrontOrder;
// ...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment