Keeping UI button State same after changing scene.

Hi, I am changing the sprite and text of my button when I press it through script in a scene. But when I go to another scene and come back to this scene the buttons return to their default. How to I avoid this and keep buttons the same as they were when I pressed them.

You could have an object with a ButtonState script on, that keeps track of the last state that the button had before switching scenes. This is useful, because that gameobject can be set to DontDestroyOnLoad, which means it won’t refresh the state or be destroyed OnSceneLoad. For example:

public class ButtonState : MonoBehaviour
{
    private static ButtonState instance;

    public Button button;

    // Keeps reference of last button state
    public Text ButtonText;
    public Image ButtonSprite;

    private void Awake()
    {
        // Singleton that prevents two of the
        // same objects from being in the same scene
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
    }

    public void OnSceneLoad()
    {
        button.GetComponent<Text>().text = ButtonText.text;
        button.image = ButtonSprite;
    }
}

Before switching scenes, you should set the ButtonText and ButtonSprite of the ButtonState script to the button’s current state values. This will allow you to load them back OnSceneChange.


The public method OnSceneLoad() should be called after you move scenes. This updates the button’s state to its previous state before switching scenes. However, remember you will need to re-reference your button in your scene before running the method, to make sure the effects are applied to the right button. Hope that helps @bhavuK