Question by
Dubz_skrrt · Oct 13, 2021 at 12:37 PM ·
buttonspriteeventsystemui image
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.
screenshot-2.jpg
(37.3 kB)
screenshot-1.jpg
(45.1 kB)
Comment
Best Answer
Answer by Dubz_skrrt · Oct 14, 2021 at 12:10 PM
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.