Player Mesh fade from one color to another

Im trying to have a flash of a color every time the enemy is hit and then have it fade from blue to red. Here is my current code.

var hitPoints = 100.0;
var deadReplacement : Transform;
var dieSound : AudioClip;
var colorStart1 = Color.blue;
var colorEnd1 = Color.blue;
var colorStart2 = Color.red;
var colorEnd2 = Color.red;
var playerMesh : Renderer;
var duration = 1.0;
var lerp = (Time.time - duration) / duration;

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

    if (hitPoints >= 51){   
    playerMesh.material.color = Color.Lerp (colorStart1, colorEnd1, lerp);
    }

    if (hitPoints <= 50){   
    playerMesh.material.color = Color.Lerp (colorStart2, colorEnd2, lerp);
    }

    hitPoints -= damage;

    if (hitPoints <= 0.0)
    {
        Detonate();
    }
}

You didn't say what your problem was, so I'm going to assume that the character isn't changing color. You have a couple problems.

  1. colorStart1 and colorEnd1 are both Color.blue. Given the Lerp formula is (1 - t) * a + t * b, if both “a” and “b” are blue, then any value in between them will also be blue. The same applies for colorStart2.

2.The next problem is related to the t in the Lerp formula. The "lerp" var will always = -1, so in Lerp it is clamped at 0. What it appears you are trying to do is have it fade from one color to another over 1 second. Then you might want to look at something like:

var hitPoints = 100.0;
var deadReplacement : Transform;
var dieSound : AudioClip;
var colorStart1 = Color.blue;
var colorEnd1 = Color.blue;
var colorStart2 = Color.red;
var colorEnd2 = Color.red;
var playerMesh : Renderer;
var duration = 1.0;

var col : Color;
var changingColor = false;

function Start () {
    col = playerMesh.material.color; //cache the current color
}

function ApplyDamage (damage : float) {
    if(!changingColor) { 

        changingColor = true;
        hitPoints -= damage;

        if (hitPoints <= 0.0)
            return;

        if (hitPoints >= 51){   
            LerpColor(col, colorEnd1, duration);
        }

        else if (hitPoints <= 50){   
            LerpColor(col, colorEnd2, duration);
        }

        if (hitPoints <= 0.0)
        {
        }
    }
}

function LerpColor (start : Color, end: Color, time : float) {
    var i : float = 0;
    while(i <= 1) {
        col =  Color.Lerp(start, end , i);
        playerMesh.material.color = col;
        i += Time.deltaTime / time;
        yield;
    } 
    changingColor = false;
} 

This will change the objects color from the current color to the set color over the duration. The changingColor boolean should prevent LerpColor being called over and over while it is still running. This way, If you are still changing color, you cannot take anymore damage until you finish taking damage. I didn't test it though. Hope this helps some.