Friday, August 14, 2015

c# - Change the sprite of a Object in Unity


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?



Answer



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(); // 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 :)


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...