用代码场景Spine人物

时间:2021-09-06 14:23:33
在使用Spine动画的时候可能会需要用代码创建,所以就小小的研究了一下 

/// <summary>
/// 加载一个spine的骨骼动画
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static GameObject loadSpineAnim(string path)
{
//加载json,atlas文件;
TextAsset jsonFile = AssetDatabase.LoadAssetAtPath<TextAsset>(@"Assets\" + path + ".json");
TextAsset atlasFile = AssetDatabase.LoadAssetAtPath<TextAsset>(@"Assets\" + path + ".atlas.txt"); //解析图片个数;就是材质个数;
string atlasStr = atlasFile.ToString();
string[] atlasLines = atlasStr.Split('\n');
List<string> _lsPng = new List<string>();
for (int i = ; i < atlasLines.Length - ; i++)
{
if (atlasLines[i].Length == )
_lsPng.Add(atlasLines[i + ]);
}
//创建材质;
Material[] maters = null;
if (_lsPng != null)
{
maters = new Material[_lsPng.Count];
string pngPath = path.Replace("/", @"\");
int pos = pngPath.LastIndexOf(@"\");
pos++;
pngPath = pngPath.Remove(pos, pngPath.Length - pos);
for (int i = ; i < _lsPng.Count; i++)
{
maters[i] = new Material(Shader.Find("Spine/Skeleton"));
maters[i].mainTexture = LY.ResLoad.loadImage(pngPath + _lsPng[i]).texture;
}
}
//创建一个atlas;
AtlasAsset atlasAsset = ScriptableObject.CreateInstance<AtlasAsset>();
atlasAsset.atlasFile = atlasFile;
atlasAsset.materials = maters;
atlasAsset.Reset(); //创建一个spine插件的动画文件,并初始化数据;
SkeletonDataAsset skeletonDataAsset = SkeletonDataAsset.CreateInstance<SkeletonDataAsset>();
skeletonDataAsset.atlasAssets = new AtlasAsset[] { atlasAsset };
skeletonDataAsset.skeletonJSON = jsonFile;
skeletonDataAsset.fromAnimation = new string[];
skeletonDataAsset.toAnimation = new string[];
skeletonDataAsset.duration = new float[];
skeletonDataAsset.scale = 0.01f; //创建出来动画的渲染大小;
skeletonDataAsset.Reset(); //开始创建GameObject;
GameObject obj = new GameObject(jsonFile.name);
//加上动画组件;
SkeletonAnimation skelet = obj.AddComponent<SkeletonAnimation>();
skelet.skeletonDataAsset = skeletonDataAsset;
skelet.transform.localPosition = new Vector3(100f, 0f, 0f);
skelet.transform.localScale = new Vector3(1f, 1f, 1f);
skelet.Reset(); return obj;
}