Reputation: 29
I am developing a small project by Unity3D. In project there are some keys. when I click a key the key's transparency will be smoothly change to 50% to 100% and this change will take 0.5 sec. So I need animation of the option transparency. Is it possible in Unity3D to smoothly animate of a object's transparency?
Upvotes: 3
Views: 4191
Reputation: 11933
You should Lerp inside the Update
loop to change the color. Use the Time
class to measure time. Check the Lerp
documentation for an example.
I also found this code, it changes the transparency using Lerp
but not exactly the way you want, and it's unityscript, unfortunately:
#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;
}
UPDATE
The answer above is still valid but I want to recommend using DOTween, a free plugin with option to go pro that does all sorts of lerps - color, positions, rotations, alpha, etc. It's really easy to use, have good performance and I've been using it in multiple projects.
Upvotes: 3
Reputation: 56
if your script is a c# script:
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);
}
}
Upvotes: 2