Destory and Fade - almost got it, but...

I cobbled this script together in an attempt to fade out an object after its hitpoints are < 0, followed by a destroy object command. I don’t understand why it is crashing Unity every time I run it. Does anyone have a solution?

Thanks,

Greg

var hitPoints = 100.0;
var deadReplacement : Transform;
var dieSound : AudioClip;
var initialDelay = 1.0;
var fadeSpeed = 1.0;

function ApplyDamage (damage : float) {
	// We already have less than 0 hitpoints, maybe we got killed already?
	if (hitPoints <= 0.0)
		return;

	hitPoints -= damage;
	if (hitPoints <= 0.0)
	{
		
		
		
renderer.material.color.a = 1.0;

yield new WaitForSeconds(initialDelay);

while (renderer.material.color.a > 0.0)

   color = renderer.material.color;
   color.a = 0.0;
   renderer.material.color = Color.Lerp(renderer.material.color, color, fadeSpeed * Time.deltaTime);
   
   yield;
		
		Detonate();
	}
}

function Detonate () {
	// Destroy ourselves
	Destroy(gameObject);
	
	// Play a dying audio clip
	if (dieSound)
		AudioSource.PlayClipAtPoint(dieSound, transform.position);

	// Replace ourselves with the dead body
	if (deadReplacement) {
		var dead : Transform = Instantiate(deadReplacement, transform.position, transform.rotation);
		

			}
			
			
	}

The main problem is this:

while (renderer.material.color.a > 0.0)

   color = renderer.material.color;

That’s an infinite loop, since renderer.material.color.a will never change, and will always be above 0.0. Unity freezes because there’s no way to break an infinite loop if there’s no yield in it. You need to enclose the entire loop in braces if you want it to execute…you can leave them out for one line loops, but I don’t recommend it for this reason (makes things inconsistent). Unless you’re using Boo; then you don’t need braces. You can try something like this:

function ApplyDamage (damage : float) { 
	// We already have less than 0 hitpoints, maybe we got killed already? 
	if (hitPoints <= 0.0) 
		return; 

	hitPoints -= damage; 
	if (hitPoints <= 0.0) 
	{
		renderer.material.color.a = 1.0; 
		yield WaitForSeconds(initialDelay); 
		
		var t = 1.0;
		while (t > 0.0) {
			t -= fadeSpeed * Time.deltaTime;
			renderer.material.color.a = t; 
	
			yield;
		}
		Detonate(); 
	} 
}

–Eric

That worked perfectly! Thanks for the education and coming to my rescue, again- especially on a Sunday!

Enjoy the weekend,

Greg