Oscar Reyes
Oscar Reyes

Reputation: 4352

Unity. How to change sprite in script

i'm trying to make a sprite to be changed on specific button, i've already tried this code:

#pragma strict

var velocity : int = 8;
var sprite : SpriteRenderer;

function Start ()
{
    sprite = GetComponent(SpriteRenderer);
}

function Update ()
{
    if(Input.GetKey(KeyCode.LeftArrow))
    {
        sprite.sprite = Resources.Load("mario_3", typeof(Sprite));
        transform.Translate(Vector2.right * -1 * velocity * Time.deltaTime);
    }

    if(Input.GetKey(KeyCode.RightArrow))
    {
        sprite.sprite = Resources.Load("mario_3", typeof(Sprite));
        transform.Translate(Vector2.right * velocity * Time.deltaTime);
    }
}

here i'm just interested in the sprite, i've got a multiple sprite splited but when i press the button to see if it works, the sprite disappears, i made a debug log on it to see what is going on and what it prompts is that script is being null when it tries to change.

i've seen some examples through the internet and they did not help, i also looked through the script reference and it does not seem to be that helpful in this case

Upvotes: 1

Views: 9919

Answers (2)

MaikonFarias
MaikonFarias

Reputation: 706

You can create the variables for sprites at the beginning of the script then set them in the inspector.

var spriteMario3: Sprite;

Then later you can use it inside your script:

sprite.sprite = spriteMario3;

But remember that you need to change the spriteMario3 from inspector in the UnityEditor.

I hope it helps you.

Your code would look like this:

#pragma strict

var spriteMario3: Sprite;
var spriteMario4: Sprite;

var velocity : int = 8;
var sprite : SpriteRenderer;

function Start ()
{
    sprite = GetComponent(SpriteRenderer);
}

function Update ()
{
    if(Input.GetKey(KeyCode.LeftArrow))
    {
        sprite.sprite = spriteMario3;
        transform.Translate(Vector2.right * -1 * velocity * Time.deltaTime);
    }

    if(Input.GetKey(KeyCode.RightArrow))
    {
        sprite.sprite = spriteMario4;
        transform.Translate(Vector2.right * velocity * Time.deltaTime);
    }
}

Upvotes: 0

Nick Udell
Nick Udell

Reputation: 2501

Firstly, does "mario_3" definitely exist in your Resources folder?

Resources.Load does not work unless it is in a Resources folder, per the Unity documentation (my bolding for emphasis):

Returns the asset at path if it can be found otherwise returns null. Only objects of type will be returned if this parameter is supplied. The path is relative to any Resources folder inside the Assets folder of your project, extensions must be omitted.

Secondly, make sure to include any sub-folders in the path name (e.g. Sprites/mario_3 if the sprite's path is Resources/Sprites/mario_3.

Finally, I'd recommend pre-loading these sprites (e.g. at Start) instead of every key press, as that could cause significant performance issues.

Upvotes: 1

Related Questions