Unity | Spine动画动态加载

目录

一、准备工作

二、Spine资源动态加载 

1.官方说明

2.注意事项

3.代码实现

3.1 动态加载json格式 

3.2 动态加载二进制格式

(1)修改SkeletonDataAsset.cs的CreateRuntimeInstance 函数,增加byte[]参数

(2)修改修改SkeletonDataAsset.cs的GetSkeletonData函数

(3)整体代码

4.效果展示


一、准备工作

        Spine插件及基本知识可查看这篇文章:Unity | Spine动画记录-CSDN博客

二、Spine资源动态加载 

1.官方说明

        官方文档指出不建议这种操作。但spine-unity API允许在运行时从SkeletonDataAsset或甚至直接从三个导出的资产实例化SkeletonAnimation和SkeletonGraphic GameObjects。

2.注意事项

        注意:动态加载的三个文件需要命名,并且不能出错。因为源代码中需要用名称来匹配。如下方的代码中要求pageName与贴图name一致,不能有后缀。

public static SpineAtlasAsset CreateRuntimeInstance (TextAsset atlasText, Texture2D[] textures, Material materialPropertySource, bool initialize) {
	// Get atlas page names.
	string atlasString = atlasText.text;
	atlasString = atlasString.Replace("\r", "");
	string[] atlasLines = atlasString.Split('\n');
	var pages = new List<string>();
	for (int i = 0; i < atlasLines.Length - 1; i++) {
		if (atlasLines[i].Trim().Length == 0)
			pages.Add(atlasLines[i + 1].Trim().Replace(".png", ""));
	}
	// Populate Materials[] by matching texture names with page names.
	var materials = new Material[pages.Count];
	for (int i = 0, n = pages.Count; i < n; i++) {
		Material mat = null;

		// Search for a match.
		string pageName = pages[i];
		for (int j = 0, m = textures.Length; j < m; j++) {
			if (string.Equals(pageName, textures[j].name, System.StringComparison.OrdinalIgnoreCase)) {
				// Match found.
				mat = new Material(materialPropertySource);
				mat.mainTexture = textures[j];
				break;
			}
		}

		if (mat != null)
			materials[i] = mat;
		else
			throw new ArgumentException("Could not find matching atlas page in the texture array.");
	}

	// Create AtlasAsset normally
	return CreateRuntimeInstance(atlasText, materials, initialize);
}

3.代码实现

3.1 动态加载json格式 

using Spine.Unity;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class DownloadSpine : MonoBehaviour
{
    public Shader shader;//选择Spine/Skeleton shader

    private TextAsset skeletonJson;//json或者二进制文件
    private TextAsset atlasText;
    private Texture2D[] textures;
    private float delay = 0;
    private string skinName="base";
    private string animationName = "gun toss";

    private SpineAtlasAsset runtimeAtlasAsset;
    private SkeletonDataAsset runtimeSkeletonDataAsset;
    private SkeletonAnimation runtimeSkeletonAnima
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烫青菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值