How do you fade out an object in a scene from an animation clip?

2.1k views Asked by At

I have a scene in Unity, with animated assets. The animated asset is a custom prefab effect with multiple animated objects nested within it. The asset runs in a loop, all the objects are assigned a PBR shader using shadergraph. Some of the assets fade out at the end, while others simply disappear. I can control when an object disappears on the timeline by disabling it. But others need to fade away. I suspect I can fade out those objects by changing the alpha of the PBR shadergraph material at a specific point in time in the animation clip. Can anyone advise the process or links to tutorials on how to fade out an object, starting at a specific point in time in an animation clip, and also set the duration required when the object becomes completely invisible ?

1

There are 1 answers

2
IndieGameDev On BEST ANSWER

To achieve what you wanted you would need to add an AnimationEvent into your Animaton.

You can do that with the Rectangle Symbol you find over the Animation Window Properties.

You can now use that AnimationEvent to call a Function in a Script that will fade out the object.

Also make sure to pass in what amount of time you want to fade the object as a float and the current GameObject as an Object into the function.

AnimationEvent Function:

public void FadeOutEvent(float waitTime, object go) {
    // Get the GameObject fromt the recieved Object.
    GameObject parent = go as GameObject;

    // Get all ChildGameObjects and try to get their PBR Shader
    List<RPBShader> shaders = parent
        .GetComponentsInChildren(typeof(RPBShader)).ToList();

    // Call our FadeOut Coroutine for each Component found.
    foreach (var shader in shaders) {
        // If the shader is null skip that element of the List.
        if (shader == null) {
            continue;
        }
        StartCoroutine(FadeOut(waitTime, shader));
    }
}

RPBShader would the Type of the Component you want to get.


To fade out the Object over time we would need to use an IEnumerator.

Fade Out Coroutine:

private IEnumerator FadeOut(float waitTime, RPBShader shader) {
    // Decrease 1 at a time, 
    // with a delay equal to the time, 
    // until the Animation finished / 100.
    float delay = waitTime / 100;
  
    while (shader.alpha > 0) {
        shader.alpha--;
        yield return new WaitForSeconds(delay);
    }
}

shader.alpha would be the current's Object PBR Shader Alpha Value that you want to decrease.