unity中实现3d物体的颜色随时间渐渐消失

实现的原理就是修改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);
    }
}

 

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值