Alpha Channel Changes Not Displayed

I’m trying to fade out a material’s alpha channel over a 1-second period with the following function.

The printed output of the countdownMaterial.color.a value is correct, however the actual alpha changes aren’t happening in either the Game window nor the Inspector window of the material. The Material is using the Mobile/Transparent/Vertex Color shader and I have the countdownMaterial assigned in the inspector as a Material. When manually updating the material in the Inspector, the alpha does what I expect. The material itself is placed on a gameObject other than where this code is located.

Does anyone see anything obviously wrong with my code?

As mentioned, the “print” statement does output the correct values.

function Countdown(seconds : float) {			// Start the 5-second countdown clock
	var mat = countdownMaterial.color.a;		// Get the current alpha value
	var fadeStartTime = Time.time;				// Set the starting time of the fade
	var fadeEndTime = Time.time + seconds;		// Set the ending time of the fade
	while(true) {								// Wait amount of time ('seconds' variable) and lerp the alpha value
		countdownMaterial.color.a = Mathf.Lerp(mat, 0, (Time.time - fadeStartTime) / (fadeEndTime - fadeStartTime));
		
		print(countdownMaterial.color.a);		// Output the value of the alpha channel
		
		if(countdownMaterial.color.a == 0) {	// Check if it's done
			runCountDown = false;				// Update the boolean and exit the function
			return;
		}
		yield;
	}
}

Thanks for any help.

1 Answer

1

Do you have countdownMaterial assigned to anything? I’d suggest making the function simpler and more generic, so it can be applied to any material. For example:

function FadeOutMaterialAlpha (mat : Material, seconds : float) {
	var t = 0.0;
	var rate = 1.0/seconds;
	while (t < 1.0) {
		t += Time.deltaTime * rate;
		mat.color.a = Mathf.Lerp (1.0, 0.0, t);
		yield;
	}
}

Then you could call it like this:

function Start () {
	FadeOutMaterialAlpha (renderer.material, 2.0);
}

That way it would fade out the material of whatever object it’s attached to.

Awesome, thanks Eric5h5. This is a simpler way of doing it and, as you say, a much more generic way of doing it. Thanks a bunch!