日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/18 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Unity动画 代码加载动画,可复用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

看了雨松的自動生成生成動畫方案,我覺得太麻煩了。所以我準備自己寫一篇代碼加載動畫方案。這個是解決幀動畫的,因為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;//定義一個變量存儲需要改變動畫的spriteprivate SpriteRenderer aniSprite;//動畫總需時間private float sumTime = 0;//記錄運行時間private float countTime = 0;private int countIndex = 0;private Sprite[] aniList;//為了避免這個代碼一直執行,我們可以在需要添加動畫的時候,再添加這個AnimationByCode的腳本//動畫結束以后,可以把動畫的gameobject destoryprivate 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 framevoid 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动画 代码加载动画,可复用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。