UI Sprite not changing when button is pressed

This is my code when button is pressed:

public void ChangeAvatar()
{

    GameObject newAvatar = EventSystem.current.currentSelectedGameObject;
    if (newAvatar != null)
    {
        Debug.Log(newAvatar.GetComponent<Image>().sprite);
        avatarImageDP.GetComponent<Image>().sprite = newAvatar.GetComponent<Image>().sprite;
    }
    else
    {
        Debug.Log("newAvatar variable is empty");
    }
}

Code works fine and all but whenever i click button, the gameObject that I referenced does not change its sprite. Been trying to solve this for a while now.

I finally solved it!

Basically what was happening was the variable avatarImageDP was not getting referenced on play mode so I added the line:

avatarImageDP = GameObject.Find(“Name of gameObject”);

inside the ChangeAvatar() function and it worked.