用代码场景Spine人物

在使用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 = 0; i < atlasLines.Length - 1; i++) { if (atlasLines[i].Length == 0) _lsPng.Add(atlasLines[i + 1]); } //创建材质; 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 = 0; 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[1] { atlasAsset }; skeletonDataAsset.skeletonJSON = jsonFile; skeletonDataAsset.fromAnimation = new string[0]; skeletonDataAsset.toAnimation = new string[0]; skeletonDataAsset.duration = new float[0]; 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; }

 

posted @ 2016-01-04 14:58  筱程  阅读(1208)  评论(1编辑  收藏  举报