Add some visual flair to your game with this simple yet powerful effect!

Unity Quick Tips: Fading an Object In and Out”

Part 4 of Our Bite-Sized Unity Tips and Tricks for Beginners

James West
3 min readFeb 16, 2023

--

Welcome to Part 4 of our series of bite-sized Unity tips and tricks for beginners! In this article, we’re going to show you how to fade an object in and out in Unity. Whether you’re creating a game or another application, fading objects can add some visual flair and make your scene more dynamic.

Here’s the code sample:

using UnityEngine;

public class FadeObject : MonoBehaviour
{
private float alpha = 0f;
private float fadeSpeed = 0.5f;
private SpriteRenderer spriteRenderer;

private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}

private void Update()
{
alpha += fadeSpeed * Time.deltaTime;
spriteRenderer.color = new Color(1f, 1f, 1f, alpha);

if (alpha >= 1f || alpha <= 0f)
{
fadeSpeed = -fadeSpeed;
}
}
}
Fade code in action. May take a moment to start.

In this script, we use the SpriteRenderer component to fade an object in and out. First, we declare a public SpriteRenderer variable and use the GetComponent method to get a reference to the component in the Start function. Then, in the Update function, we use a variable alpha to control the transparency of the object. We continuously update the alpha value by adding the product of fadeSpeed and Time.deltaTime to it. We then update the color of the object using the spriteRenderer.color property and pass in a new Color object with the updated alpha value. Finally, we add a check to see if the alpha value has reached its maximum or minimum, and if it has, we reverse the fadeSpeed to make the object fade in and out continuously.

Here are a few ways you can enhance and optimize the script for fading an object in and out in Unity:

  1. Use a Coroutine: If you have multiple objects to fade in and out, you can use a coroutine to stagger the fading over time, rather than fading all the objects at once. This…

--

--

James West

Turning my passion for video games and 11 years of software development experience into a focus on video game development using Unity3D.