Reputation: 311
Good day all.
I'm making a tower defense game in Unity3D and I'm trying to create a tower build animation.
So basically, for testing purposes, I have a primitive cube with a material with the transparent/diffuse legacy shader and I've set it's color's alpha to 0 as the tower should be completely invisible when created. It has a Tower script attached to it for the animation. I have another script which deals with the placement of the tower cube.
How do I make a tower completely visible with alpha of 255 of it's material's color when it's created over a certain amount of time?
So if the tower's build time is 5 seconds, the alpha should become from 0 to 255 in 5 seconds.
I've tried the following (Tower.cs):
public float buildTime = 10;
private MeshRenderer mr;;
private Color currentColor;
private bool built = false;
void Start() {
mr = GetComponent<MeshRenderer>()
currentColor = mr.material.color;
StartCorroutine(BuildAnimation());
}
IEnumerator BuildAnimation() {
float a = 0;
Color newColor = new Color(currentColor.r, currentColor.g, currentColor.b, a);
while (!built) {
mr.material.color = newColor;
if (a >= 255) {
built = true;
}
a+= 255 / buildTime;
yield return new WaitForSeconds(255 / buildTime);
}
}
Help will really be appreciated, thanks in advance!
Upvotes: 1
Views: 424
Reputation: 311
Thanks @Martin Mazza Dawson for the answer. Although it wasn't working properly at first I got it working with a simple fix.
IEnumerator Fade(MeshRenderer myMesh)
{
for (float t = 0f; t < FadeTime; t += Time.deltaTime)
{
float normalizedTime = t / FadeTime;
_alpha = Mathf.Lerp(_startAlpha, _endAlpha, normalizedTime);
// The fix
myMesh.material.color = new Color (myMesh.material.color.r, myMesh.material.color.g, myMesh.material.color.b, _alpha);
yield return null;
}
//_alpha = _endAlpha;
//myMesh.material.color = new Color (myMesh.material.color.r, myMesh.material.color.g, myMesh.material.color.b, _alpha);
}
Love you :)
Upvotes: 0
Reputation: 7656
[Tooltip("Time to fade in seconds")]
public float FadeTime;
private float _alpha = 0.0f;
private const float _startAlpha = 0f;
private const float _endAlpha = 1.0f;
IEnumerator Fade(MeshRenderer myMesh)
{
for (float t = 0f; t < FadeTime; t += Time.deltaTime)
{
float normalizedTime = t / FadeTime;
_alpha = Mathf.Lerp(_startAlpha, _endAlpha, normalizedTime);
yield return null;
}
_alpha = _endAlpha;
myMesh.material.color = new Color(myMesh.material.color.r,myMesh.material.color.g,myMesh.material.color.b,_alpha)
}
Then pass your Mesh through through the Fade()
.
Upvotes: 1