您的位置:首页 > 移动开发 > Unity3D

Unity动画 代码加载动画,可复用

2016-12-09 17:39 369 查看
看了雨松的自动生成生成动画方案,我觉得太麻烦了。所以我准备自己写一篇代码加载动画方案。这个是解决帧动画的,因为u3d没有播放gif的功能,有了这个神器,传入图片和总时间,就ok了。

首先我们准备一个图集,里面是播放动画的小图片。



然后创建一个sprite,放入资源文件做成profab。��,准备工作就差不多做好了。记得不要把下面这个代码添加到profab上,因为我在初始化这个profab的时候用代码添加了。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AnimationByCode :MonoBehaviour{

// Use this for initialization
//动画间隔时间
private float circleTime = 0;
//定义一个变量存储需要改变动画的sprite
private SpriteRenderer aniSprite;
//动画总需时间
private float sumTime = 0;
//记录运行时间
private float countTime = 0;
private int countIndex = 0;
private Sprite[] aniList;
//为了避免这个代码一直执行,我们可以在需要添加动画的时候,再添加这个AnimationByCode的脚本
//动画结束以后,可以把动画的gameobject destory
private void SetAnimationWithMaterial(string[] obj){
float alltime = float.Parse(obj[1].ToString());

this.aniSprite = transform.GetComponent<SpriteRenderer>();
//获取图集中所有的图片
this.aniList = Resources.LoadAll<Sprite>(obj[0].ToString());
//一张图片需要的时间
this.circleTime = alltime / this.aniList.Length;
//把图片播放完成需要多少图片
this.sumTime = alltime;

}

// Update is called once per frame
void Update () {
if (countTime < sumTime) {
countTime += Time.deltaTime;
float temp = countTime / circleTime;
if (temp >= countIndex) {
countIndex = (int)temp;
print ("countIndex" + countIndex);
//这里要剔除最后一张,如果不判断就会超过数组 越界
if (countIndex <= this.aniList.Length - 1) {
this.aniSprite.sprite =this.aniList[countIndex];
}
}

}
else if(countTime > sumTime) {
Destroy (gameObject);
}
}
}


如果要初始化这个profab,并通过生成的gameobj 传入动画需要的图片和动画总时间。

public class Example : MonoBehaviour {

public void InstanceObjectAndMakeAnimation(){

GameObject aniProfab= Resources.Load ("AniProfab")as GameObject;
GameObject aniObject = Instantiate (aniProfab,Vector3.zero,Quaternion.identity) as GameObject;
aniObject.AddComponent<AnimationByCode> ();
string[] message = new string[2];
message[0] = "connectAnim";
message[1] = "2";
aniObject.SendMessage ("SetAnimationWithMaterial",message);
}
}


动画的脚本不需要管理,只需要负责初始化profab,绑定脚本就可以了。是不是很简单!

这个只是简单加载帧动画吧,并不是万能的。如果需要循环播放,位置偏移,自己去修改下。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动画 unity 图片