click the button to change the character's sprite

I have 2 buttons. I want to change my character’s picture when I click on the buttons.How can ı do it

Here is some quick simple code to make it happen using two buttons and an image:


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

public class ImageSwap : MonoBehaviour
{
    [SerializeField] Image imageToSwap;
    [SerializeField] Sprite buttonOneImage;
    [SerializeField] Sprite buttonTwoImage;


    public void OnButtonOneClicked()
    {
        imageToSwap.sprite = buttonOneImage;
    }


    public void OnButtonTwoClicked()
    {
        imageToSwap.sprite = buttonTwoImage;
    }
}

I added the script above to an an object in your scene. Then all I did was created two UI buttons in the scene (this will create a UI canvas for you). I also added UI image as well. I linked two sprites that I wanted to change back and forth to the ImageSwap script - as well as the Image.


I then clicked on the button I added. There is a button script on them. I then when down to On Click(). Here you can hit the small + sign, this allows you to link the gameObject that your ImageSwap script is on. You can no click on the drop down, find the ImageSwap script, then pick a method to tie it to. In this case, we pick OnButtonOneClicked. This sets up a callback for when you click the button - it will call the method you picked. Next, do the same thing for the second button, but pick OnButtonTwoClicked().


Done. Start the game, click the buttons and they will swap.