Hello,
I was having a difficult time finding information on how to change a sprite using a script during runtime. I figured the Unity Documentation Scripting API should have some examples for SpriteRenderer and Sprite but there’s nothing, which was quite frustrating considering the purpose of such documentation. The only examples available were for use with the Unity Inspector, which was not what I needed. Additionally, the Unity Answers pages and the forums here seem to be a bit messy, vague, or incredibly unclear.
So this post is for everyone who is looking for such an example. I seem to have figured out the basics and thought I’d share. I hope this helps anyone looking for an example.
To give you an idea of the setup, I have the following script attached to a GameObject that only contains a SpriteRenderer component with its default values. My sprite sheet is named sprites_sheet_02, it is a .png file, it contains 62 sprites, and it’s located in the Resources folder. During runtime I load the sprites from the sprite sheet into an array. Once every update, I select a random integer from 0 to 62 and use this to get an element from the sprite array. I then set the sprite value on the SpriteRenderer component to the sprite located at the index within the sprite array.
using UnityEngine;
using System.Collections;
public class CycleSprites : MonoBehaviour
{
private int spriteIndex;
private Sprite[] spriteArray;
void Start ()
{
spriteArray = Resources.LoadAll<Sprite> ("sprites_sheet_02");
}
void Update ()
{
spriteIndex = Mathf.RoundToInt (Random.Range (-0.4f, 61.4f));
gameObject.GetComponent<SpriteRenderer> ().sprite = spriteArray[spriteIndex];
}
}
With a bit of extra code or slight modification, this script can be easily modified to choose specific sprites, not change every update, or whatever is needed to suit your goal. I hope this example helps shed light on scripting with the SpriteRenderer component and sprites.