# Change Sprites

This code can be attached to a gameObject that has a spriteRenderer, it will allow creation of a list of sprites that can be changed by calling the swapSprite( ) method.

```java
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeSprite : MonoBehaviour
{

    public List<Sprite> sprites = new List<Sprite>(); //initialize list before Start( )
    private int current;
    private SpriteRenderer spriteRenderer;
    // Use this for initialization
    void Start ()
    {
        current = 0;

        spriteRenderer = GetComponent<SpriteRenderer> ();
    }

    public void swapSprite ()
    {
        current++;
        if (current < sprites.Count) {
            spriteRenderer.sprite = sprites [current];
            Debug.Log ("Sprite changed to index " + current);
        }
    }
}
```

The image below shows the BackgroundImage GameObject, where the ChangeSprite Script has been added as a script component. Here we can see that the spriteList in the inspector has been set to hold 4 elements, then when expanded, the 4 slots have been populated with different sprites that can be swapped out for the background image.

## Use in LevelManager.cs

public void swapSprite( ) has been declared as a public method so that it can be called from the LevelManager: In order to do that, the LevelManager must create an objectReference to the ChangeSprite Script:

```
//other code above here to declare object references

ChangeSprite changeSprite;

void Start ()
    {
    //other code
    changeSprite = GameObject.Find ("BackgroundImage").GetComponent<ChangeSprite> ();
    }

//when loading Level2, the background sprite gets changed using the code below.    
void loadLevel2 ()
    {
        ///change background image
        changeSprite.SwapSprite ();
        spawner.StartSpawning ();
        levelValue.text = "2";
    }
```

![](https://1604956922-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0-KLgOacVpbicrqehO%2F-M0-KOTdBSCNJjpmpwrG%2F-M0-Kkh2ih4bGgL-U26m%2FScreenshot%202017-04-04%2011.17.55.png?generation=1581627424477639\&alt=media)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kdoore.gitbook.io/cs2335/cs2335_f20/optional-supplemental-content/optional-content/change-sprites.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
