- Home /
How to Change Character Sprite from Script
Hi, I am making Shop for my game and I want to 4 sprite images that I would like to change when I am clicking on them because I made them as prefab buttons. I watched youtube tutorial, but guy there used Material instead of sprite image that I would like to use. Here is code I have:
public GameObject shopButtonPrefab;
public GameObject shopButtonContainer;
public Sprite[] playerSkin;
private void Start()
{
ChangePlayerSkin(GameManager.instance.currentSkinIndex);
int textureIndex = 0;
Sprite[] textures = Resources.LoadAll<Sprite>("Player");
foreach(Sprite texture in textures)
{
GameObject container = Instantiate(shopButtonPrefab) as GameObject;
container.GetComponent<Image>().sprite = texture;
container.transform.SetParent(shopButtonContainer.transform, false);
int index = textureIndex;
container.GetComponent<Button>().onClick.AddListener(() => ChangePlayerSkin(index));
textureIndex++;
}
}
private void ChangePlayerSkin(int index)
{
Debug.Log(index); // here should be code for changing sprite image
GameManager.instance.currentSkinIndex = index;
GameManager.instance.Save();
}
Please Help if you know the solution. Thanks in advance.
Comment