我正在开发Unity3D的一个小项目。在项目中有一些键。当我单击某个键时,该键的透明度将平滑地更改为50%到100%,此更改将花费0.5秒。所以我需要选项透明度的动画。在Unity3D中是否可以平滑地为对象的透明度设置动画?
您应该在Lerp循环内的Update
更改颜色。使用Time
类来测量时间。有关示例,请参阅Lerp
文档。
我也找到了这段代码,它使用Lerp
更改了透明度,但并不完全是您想要的方式,不幸的是,它是unityscript:
#pragma strict
var duration : float = 1.0;
var alpha : float = 0;
function Update(){
lerpAlpha();
}
function lerpAlpha () {
var lerp : float = Mathf.PingPong (Time.time, duration) / duration;
alpha = Mathf.Lerp(0.0, 1.0, lerp) ;
renderer.material.color.a = alpha;
}
更新
上面的答案仍然有效,但我想推荐使用DOTween,这是一个免费的插件,具有前往pro的选项,可以处理各种问题-颜色,位置,旋转度,alpha等。它确实易于使用,具有良好的性能,我已经在多个项目中使用了它。
如果您的脚本是C#脚本:
using UnityEngine;
using System.Collections;
public class WebPlayerController : MonoBehaviour {
public bool selected = false;
//Setting the colors like this, you can change them via inspector
public Color enabledColor = new Color(1,1,1,1);
public Color disabledColor = new Color(1,1,1,0.5f);
public float transitionTime = 0.5f;
private float lerp = 0;
void Start(){
lerp = selected ? 1 : 0;
}
//You can set by this method the button state! :)
public void SetSelected(bool isSelected){
selected = isSelected;
}
void Update(){
lerp += (isSelected ? 1 : -1) * Time.deltaTime/transitionTime;
lerp = Mathf.Clamp01 (lerp);
renderer.material.color = Color.Lerp(disabledColor,enabledColor,lerp);
}
}