[Resolved] Image not changing on Toggle

Here’s my code

public class MusicPlay : MonoBehaviour {

    public SpriteRenderer toggle;
    private bool music = true;
    public Sprite on; 
    public Sprite off;

    public void ToggleMusic () {
        Debug.Log("Toggle pressed");
        musicOn = !musicOn;
        if (music) 
        {
            toggle.GetComponent<SpriteRenderer>().sprite = on;
            Debug.Log("Toggle image: " + on);
        } 
        else 
        {
            toggle.GetComponent<SpriteRenderer>().sprite = off;
            Debug.Log("Toggle image: " + off);
        }
    }

}

And my log messages are

Toggle (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)
MusicPlay:Start() (at Assets/Scripts/MusicPlay.cs:24)

Toggle pressed
UnityEngine.Debug:Log(Object)
MusicPlay:ToggleMusic() (at Assets/Scripts/MusicPlay.cs:33)
UnityEngine.EventSystems.EventSystem:Update()

Toggle image: musicOff 1 (UnityEngine.Sprite)
UnityEngine.Debug:Log(Object)
MusicPlay:ToggleMusic() (at Assets/Scripts/MusicPlay.cs:40)
UnityEngine.EventSystems.EventSystem:Update()

Since it prints out the Sprite name, I’m fairly sure the assignment was done properly. It may be something to do with the SpriteRenderer? The toggle was done by adding an Image to the canvas, then adding the Toggle component to the object, then finally adding a SpriteRenderer component on top of it. I just dragged the game object into the SpriteRenderer field.

So I tried using Image instead and it worked perfectly. Still not sure what’s wrong with the code above, but if anyone is facing the same issue…

 public class MusicPlay : MonoBehaviour {
 
     public Image toggle;
     private bool music = true;
     public Sprite on; 
     public Sprite off;
 
     public void ToggleMusic () {
         musicOn = !musicOn;
         if (music) 
         {
             toggle.GetComponent<Image>().sprite = on;
         } 
         else 
         {
             toggle.GetComponent<Image>().sprite = off;
         }
     }
 
 }

This worked.