实现的原理就是修改material的color属性的Alpha值,通过把值逐渐变为0来达到消失
注意:这种方法只对部分shader有作用,我用的是
下面是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
//设置渐变的时间
public float timeCout;
private void Update()
{
//按鼠标左键开始渐变
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(ChangeFormTime(timeCout));
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log(this.GetComponent<Renderer>().material.color.a);
}
}
//开启协程物体开始渐变
IEnumerator ChangeFormTime(float _timeCout)
{
while (_timeCout>0)
{
//倒计时
_timeCout -= Time.deltaTime;
if (this.GetComponent<Renderer>().material.color.a > 0)
{
this.gameObject.GetComponent<Renderer>().material.color = new Color(
this.GetComponent<Renderer>().material.color.r,
this.GetComponent<Renderer>().material.color.g,
this.GetComponent<Renderer>().material.color.b,
//会根据你输入的时间进行渐变
this.GetComponent<Renderer>().material.color.a - Time.deltaTime / timeCout);
yield return null;
}
}
//虽然是透明的但是还在渲染,为了减少Drawcall,可以
//1.隐藏物体2.摧毁物体3.移除到摄像机拍不到的地方
this.gameObject.SetActive(false);
}
}