Inside the script code of the the hero(object) I want add the possibility to change its sprite.

So the player hits the space button and the sprite changes into the other sprite already added to the project.

Can you provide me a sample code to do this?

  • 1
    \$\begingroup\$ Although the function for changing sprites below should work exactly as you have asked, I would suggest that you look into the Unity animator. Usually when people change sprites it is to create an animation for an action (such as swinging a sword or opening a door) and this is typically done in more basic engines by swapping the sprites manually. Unity however has built in support for animations allowing you to create an animation file for all sprites needed, then allowing you to tell the game to play them automatically given certain conditions in the animation controller. \$\endgroup\$ May 18, 2016 at 0:32

1 Answer 1


The code has been commented for you. Enjoy.

public Sprite sprite1; // Drag your first sprite here
public Sprite sprite2; // Drag your second sprite here

private SpriteRenderer spriteRenderer; 

void Start ()
    spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
    if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
        spriteRenderer.sprite = sprite1; // set the sprite to sprite1

void Update ()
    if (Input.GetKeyDown (KeyCode.Space)) // If the space bar is pushed down
        ChangeTheDamnSprite (); // call method to change sprite

void ChangeTheDamnSprite ()
    if (spriteRenderer.sprite == sprite1) // if the spriteRenderer sprite = sprite1 then change to sprite2
        spriteRenderer.sprite = sprite2;
        spriteRenderer.sprite = sprite1; // otherwise change it back to sprite1

You need to have a sprite renderer attached to your GameObject. Create a new C# Script and attach to it a GameObject. Paste the code in between the parenthesis... I'm sure you can figure it out from there :)

  • \$\begingroup\$ you sir, are a legend. \$\endgroup\$
    – jack
    Jul 17, 2017 at 0:22
  • \$\begingroup\$ @Savlon this makes no sense "we are accessing the SpriteRenderer that is attached to the Gameobject" what gameobject??? where was it referenced? where's the name? where's the path? I want to set the sprite of a gameobject. how do I reference that game object and set it's sprite? \$\endgroup\$
    – tatsu
    Feb 11, 2021 at 10:22
  • \$\begingroup\$ @tatsu that isn’t the full script. You need to paste that into your monobehaviour inherited class that is attached to your gameobject. The “GetComponent” call searches the gameobject the script is attached to for a spriterenderer. \$\endgroup\$
    – Savlon
    Feb 11, 2021 at 10:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .