Tuesday, January 23, 2018

unity - How can I fade a game object in and out over a specified duration?


I would like to know how I can fade a game object in and out. I would like to achieve this using a C# script. As I am quite new to Unity I've read about coroutines but still haven't fully grasped the concept. I would appreciate some assistance.



Answer



Assuming you've already configured your material in the Inspector to use transparent blending (otherwise it will ignore the mucking with alpha we're doing below), you can use a simple coroutine like this:


(If using a SpriteRenderer, you'd modify the color property of the SpriteRenderer rather than passing the material, but the rest can stay the same)


// Define an enumerator to perform our fading.
// Pass it the material to fade, the opacity to fade to (0 = transparent, 1 = opaque),

// and the number of seconds to fade over.
IEnumerator FadeTo(Material material, float targetOpacity, float duration) {

// Cache the current color of the material, and its initiql opacity.
Color color = material.color;
float startOpacity = color.a;

// Track how many seconds we've been fading.
float t = 0;


while(t < duration) {
// Step the fade forward one frame.
t += Time.deltaTime;
// Turn the time into an interpolation factor between 0 and 1.
float blend = Mathf.Clamp01(t / duration);

// Blend to the corresponding opacity between start & target.
color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);

// Apply the resulting color to the material.

material.color = color;

// Wait one frame, and repeat.
yield return null;
}
}

You can use this like so:


// .material getter clones the material, 
// so cache this copy in a member variable so we can dispose of it when we're done.

_myMaterial = GetComponent().material;

// Start a coroutine to fade the material to zero alpha over 3 seconds.
// Caching the reference to the coroutine lets us stop it mid-way if needed.
_currentFade = StartCoroutine(FadeTo(_myMaterial, 0f, 3f));

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...