写代码要有风险意识

     好久没有更文了,以前几乎是每天一篇。为啥现在慢了?不是因为偷懒了,而是因为平时花大量的时间在做项目的内容。记得师兄以前也是,他每个月都更一两篇文,主要现在把时间放在项目的打磨上。

    现在谈的主题是写代码要有风险意识,如果没有这个意识,你会发现你的代码有很大风险和问题。今天遇到一个奇葩的问题:我做一个渐隐渐现的需求,代码如下:

              if(is_ice){//is_iceif (tempTime01 < 0.3f) { tempTime01 = tempTime01 + Time.deltaTime;}dahan_I.GetComponent().material.color = new Color(dahan_I.GetComponent().material.color.r,dahan_I.GetComponent().material.color.g,dahan_I.GetComponent().material.color.b,//需要改的就是这个属性:Alpha值           dahan_I.GetComponent().material.color.a+tempTime01/300);}if(is_ice01){if (tempTime02 < 0.3f) { tempTime02 = tempTime02+ Time.deltaTime;}dahan_I.GetComponent().material.color = new Color(dahan_I.GetComponent().material.color.r,dahan_I.GetComponent().material.color.g,dahan_I.GetComponent().material.color.b,//需要改的就是这个属性:Alpha值           dahan_I.GetComponent().material.color.a-tempTime02/300);}

判断条件是:是否结冰。

当我这样做的时候,程序能运行起来,效果也有。可是在持续的过程中发现,突然无法再现这样的效果。后来我查看材质球变灰了,于是我认为是材质丢失的问题,重新建立一个。没想到“天公不作美”,问题还是存在。

于是我改了tempTime值,设置它在tempTime>0.3f的情况下等于零(重设值);可是还是不行。

后面我对整个代码进行分析和考虑,上面的代码有问题和风险,如下:

if(is_ice01){if (tempTime02 < 0.3f) { tempTime02 = tempTime02+ Time.deltaTime;}dahan_I.GetComponent().material.color = new Color(dahan_I.GetComponent().material.color.r,dahan_I.GetComponent().material.color.g,dahan_I.GetComponent().material.color.b,//需要改的就是这个属性:Alpha值           dahan_I.GetComponent().material.color.a-tempTime02/300);}

即:dahan_I.GetComponent().material.color.a的值在不断的减小,没有进行限制和取范围,因为它在无穷减小,于是进行针对性的修改:

if(dahan_I.GetComponent().material.color.a<0.0f){dahan_I.SetActive(true);dahan_I.GetComponent().material.color = new Color(dahan_I.GetComponent().material.color.r,dahan_I.GetComponent().material.color.g,dahan_I.GetComponent().material.color.b,//需要改的就是这个属性:Alpha值           0f);}

当dahan_I.GetComponent().material.color.a<0.0f时,重设它的alpha值为零。果然是这个问题。

当然写代码是多种尝试,这种渐隐渐现的需求,可以通过Dotween插件一行搞定,而且也会避免这样的问题。如:

GetComponent().material.DOColor(new Vector4(1,1,1,0), 1.0f);

所以在写代码的过程中一定要思考,我这样写会产生什么风险和问题。


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部