0
0
Unityframework~5 mins

Sprite Renderer component in Unity

Choose your learning style9 modes available
Introduction

The Sprite Renderer component shows 2D images (sprites) on the screen in Unity. It helps you display characters, objects, and backgrounds in your game.

When you want to show a character or object in a 2D game.
When you need to display a background image or scenery.
When you want to animate a 2D sprite by changing its image.
When you want to control the color or transparency of a 2D image.
When you want to layer multiple sprites to create depth.
Syntax
Unity
gameObject.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = yourSprite;
spriteRenderer.color = Color.white;
spriteRenderer.sortingOrder = 0;

You add the Sprite Renderer component to a GameObject to show a sprite.

You can change the sprite image, color, and draw order with this component.

Examples
Adds a Sprite Renderer and sets its image to mySprite.
Unity
SpriteRenderer sr = gameObject.AddComponent<SpriteRenderer>();
sr.sprite = mySprite;
Changes the sprite color to semi-transparent red.
Unity
spriteRenderer.color = new Color(1f, 0f, 0f, 0.5f);
Sets the draw order so this sprite appears above sprites with lower sorting orders.
Unity
spriteRenderer.sortingOrder = 5;
Sample Program

This script adds a Sprite Renderer to the GameObject it is attached to. It sets the sprite image to mySprite, makes sure the color is white (no tint), and sets the draw order to 1 so it appears above default sprites.

Unity
using UnityEngine;

public class ShowSprite : MonoBehaviour
{
    public Sprite mySprite;

    void Start()
    {
        SpriteRenderer sr = gameObject.AddComponent<SpriteRenderer>();
        sr.sprite = mySprite;
        sr.color = Color.white;
        sr.sortingOrder = 1;
    }
}
OutputSuccess
Important Notes

Make sure your sprite image is imported as a Sprite in Unity.

You can control transparency with the color's alpha value (0 = invisible, 1 = fully visible).

Sorting order controls which sprites appear on top when they overlap.

Summary

The Sprite Renderer component displays 2D images on GameObjects.

You can change the sprite image, color, and draw order with it.

It is essential for showing characters and objects in 2D Unity games.