在做粒子效果时,想替换材质的图片,但是材质没有获取图片名称的属性,只能将图片转换成纹理付给材质的mainTexture,,写了个脚本,每两秒换材质图片,一分钟后销毁粒子效果,如:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EffectForFestival : MonoBehaviour
{
public List<GameObject> mChildrens;
float mDeltaTime = 0;
float mTotalTime = 2;
float mDeltaDestroyTime = 0;
float mDestroyTime = 60;
private GameObject balloonEffctMgr;
void Start()
{
Object o = Resources.Load("GUI/Effect/BalloonEffectMgr");
balloonEffctMgr = Instantiate(o) as GameObject;
}
//----------------------------------------------------------------------------------------------------------------------
public void ChangeTexture(int num)
{
foreach (GameObject item in mChildrens)
{
if (num>18)
{
num = 1;
}
item.GetComponent<ParticleSystem>().renderer.material.mainTexture = (Texture2D)Resources.Load("Effect/image/" + change(num));//换材质
num += 1;
}
}
//----------------------------------------------------------------------------------------------------------------------
string change(int num)
{
string id = "";
if (num<10)id = "0" + num;
else if (num > 18)id = "01";
else id = num.ToString();
return id;
}
//----------------------------------------------------------------------------------------------------------------------
void Update ()
{
mDeltaTime+=Time.deltaTime;
mDeltaDestroyTime += Time.deltaTime;
if (mDeltaDestroyTime>=mDestroyTime)
{//3分钟销毁
Destroy(this.gameObject);
}
if (mDeltaTime > mTotalTime)
{//两秒换材质
int number = UnityEngine.Random.Range(1, 18);
ChangeTexture(number);
mDeltaTime = 0;
}
}
void OnDestroy()
{
if (balloonEffctMgr != null)
{
balloonEffctMgr.GetComponent<BalloonEffectMgr>().DestoryObject();
}
}
}