- Home /
Fading blood pool on ground.
Hi I have been trying to create a blood pool everytime I kill a victim It turned out to be a bit more difficult than expected, and I fear that my end result.. although it works, is not the optimal sollution. I would be very gratefull, if someone had suggestions on how to do this in a better way. So, if anyone has offers on how to improve this, please share with me.
using UnityEngine;
using System.Collections;
public class AlphaFader : MonoBehaviour
{
public Texture2D blood;
public Color lerpedColor;
public bool startFading = false;
public float trans = 1;
void Start ()
{
//Sets the material of the gameObject
renderer.material = new Material (Shader.Find ("Transparent/Diffuse"));
renderer.material.SetTexture("_MainTex", blood);
//Starts the corutine
StartCoroutine(StartFading());
}
void Update ()
{
if(startFading){
//Removes some of the trans that is used to lert the alpha of the material.
trans = trans - Time.deltaTime * 0.2f;
lerpedColor.a = Mathf.Lerp(0, 1, trans);
renderer.material.color = lerpedColor;
}
//Destroys the object when the material is completly transparent.
if (lerpedColor.a == 0)
Destroy (this.gameObject);
}
//This will waith for a while before starting the fade of the material.
IEnumerator StartFading (){
yield return new WaitForSeconds(Random.value * 4.0f);
startFading = true;
}
}
Well apart from you don't need the Lerp the way it is:
lerpedColor.a = trans;
Answer by Mortoc · Jun 25, 2012 at 11:15 PM
You can save some trouble by using Start as the coroutine and doing the for/time coroutine pattern (example below), but other than that I'd say your script looks fine! Only reason I suggest switching to this pattern is that it's easier to maintain and tweak.
public class AlphaFader : MonoBehaviour
{
public Texture2D blood;
public float fadeTime = 3.0f;
IEnumerator Start ()
{
//Sets the material of the gameObject
renderer.material = new Material (Shader.Find ("Transparent/Diffuse"));
renderer.material.SetTexture("_MainTex", blood);
yield return new WaitForSeconds(Random.value * 4.0f);
//Removes some of the trans that is used to lerp the alpha of the material.
float invFadeTime = 1.0f / fadeTime;
for(float t = 0.0f; t < fadeTime; t += Time.deltaTime)
{
Color bloodColor = renderer.material.color;
bloodColor.a = Mathf.Lerp(1.0f, 0.0f, t * invFadeTime);
renderer.material.color = bloodColor;
yield return 0;
}
//Destroys the object when the material is completly transparent.
Destroy (this.gameObject);
}
}
Your answer
Follow this Question
Related Questions
How to change the alpha element of particles/additive color? 1 Answer
Color.Lerp not lerping 2 Answers
Fade-In/Out shadows for a specific object 0 Answers
Color lerp once? 2 Answers