Crocus
Crocus

Reputation: 97

Changing a sprite at runtime in unity

Is there a way for me to alter the following script to change a specific sprite?

I would like to change a Sprite called Background1 to another one called Background2 when the score is at a specific number.

For example to change the Sprite when the score is 25.

public class Score : MonoBehaviour 
{
    private static int score = 0;
    private static int highScore = 0;

    public static void AddPoint() 
    {
        score++;

        if (score > highScore)
            highScore = score;
    }

    private void Start() 
    {
        score = 0;
        highScore = PlayerPrefs.GetInt("highScore", 0);
    }

    private void OnDestroy() => PlayerPrefs.SetInt("highScore", highScore);
    private void Update()    => guiText.text = "Score: " + score + "\nHigh Score: " + highScore;
}

Upvotes: 1

Views: 4337

Answers (1)

Siddharth
Siddharth

Reputation: 4312

For this implementation you have to create sprite array as per your required size.

public Sprite[] backgrounds;

Manage counter for your background and accessing sprite renderer component, you can change background your game.

GetComponent<SpriteRenderer>().sprite = backgrounds[index];

I think now you got my point. If you want any more detail related to my then comment it.

Upvotes: 3

Related Questions