Public static variable in Unity

We can use a static variable so that it’s value can be transferred between the scenes. There are other options to achieve the same result but using a static variable within a singleton is one of the simplest to implement.
We will create two Scenes, then add a Text field tagged txtCounter to each of them so that we can easily make a relation between the script and text objects. Next, we will create an Empty GameManager object, GManager script (and make it a singleton) and attach the script to the empty in both scenes. Create buttons and assign the public function so that we will be able to switch between the scenes. Don’t forget to add Scenes in the build settings.

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

public class GManager : MonoBehaviour
{
    public static GManager instance;

    Text txt_sceneName;

    public static float counter = 1;

    void Awake()
    {
        if(instance == null)
        {
            instance = this;
        }else if(instance != this)
        {
            Destroy(gameObject);
        }
    }
    void Start()
    {
        txt_sceneName = GameObject.FindGameObjectWithTag("txtCounter").GetComponent<Text>();
        
    }

    void Update()
    {
        counter += Time.deltaTime;
        txt_sceneName.text = counter.ToString();
    }

    public void GoToOtherScene()
    {
        if(SceneManager.GetActiveScene().buildIndex == 0)
        {
            SceneManager.LoadScene(1);
        }
        else if(SceneManager.GetActiveScene().buildIndex == 1)
        {
            SceneManager.LoadScene(0);
        }
    }
}

Now, we should see counting going on regardless of the scene we are switched to.

The GManager script is being shared between both scenes.