Changing sprite through script?

Hey, how do I change the GameObject’s sprite which the following script which is not working, is attached to?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Check : MonoBehaviour
{
    //Reference
    private Scoreboard scoreboard;

    Sprite player;
    public Sprite char1;

    void Start ()
    {
        player = this.GetComponent<Sprite> ();
        // Reference
        GameObject GM = GameObject.Find("GM");
        scoreboard = GM.GetComponent<Scoreboard>();


    }

    void Update ()
    {
        if (scoreboard.Character1 == true)
        {
            player = char1;
        }
    }
}

Nothing happens when score.Character1 = true?

What are you expecting to happen? As far as I can tell all you are doing in update is assigning char1 to the player variable everyframe after scoreboard.Character1 becomes true.

If you want to see a visual representation of this, you should probably be assigning char1 to the sprite property of a UI Image. (But even then you probably only want to do this once, rather than in update).

1 Like

Try changing “player” to the type SpriteRender (and the get component call, too)
Then, set player.sprite = char1;

Agreed that it would be much better to simply switch it when you change the character (or choose the character – whatever that situation is), as opposed to inside Update()
:slight_smile:

So I guess it should look something like this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Check : MonoBehaviour
{
    //Reference
    private Scoreboard scoreboard;

    Sprite player;
    public Sprite char1;

    void Start ()
    {
        player = this.GetComponent<SpriteRenderer> ();
        // Reference
        GameObject GM = GameObject.Find("GM");
        scoreboard = GM.GetComponent<Scoreboard>();

        if (scoreboard.Character1 == true)
        {
            set player.sprite = char1;
        }

    }
}

But I get the error: “Assets/Check.cs(22,13): error CS1525: Unexpected symbol .', expecting ,‘, ;', or =’”

No, no…See at the top you still called player (type) “Sprite”.
and you don’t want “set player.sprite = char1”
you want:

player.sprite = char1;
1 Like

There we go!
You have saved my life today man ^^

:slight_smile: Cool, glad it’s working for ya.