11
\$\begingroup\$

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?

\$\endgroup\$
  • 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\$ – Benjamin Danger Johnson May 18 '16 at 0:32
19
\$\begingroup\$

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;
    }
    else
    {
        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 :)

\$\endgroup\$
  • \$\begingroup\$ you sir, are a legend. \$\endgroup\$ – kal kokah Jul 17 '17 at 0:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.