How to create script linked to scene?

Hi, i create a script “finish.cs”, it have 2 public values:



that are changeable from inspecor. I want to make this script universal for each scene, but when i edit eg. maxScore in scene 1, this value is assigned aslo to maxScore from scene 2. How can i avoid this?
here is my code:

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

public class finish : MonoBehaviour {

    public TextMesh textMesh;   //connect score display text
    public int maxScore = 3;    //max score on level
    public string next_level;   //next level name

    void Start()

    private void OnTriggerEnter(Collider collision)
        if ( == "Sphere")
            string wynik = textMesh.text;       //conversion of score
            int Iwynik;                         //to int and check if
            int.TryParse(wynik, out Iwynik);    //its equal to max score

            if (Iwynik == maxScore)
                Debug.Log("level change");      //just debug
                textMesh.text = "0";                    //score reset
                SceneManager.LoadScene(next_level);     //load next scene

        Debug.Log(;   //just debug


When you hit run:

  • finish.class is created and maxScore
    is assigned to 3
  • When you switch scenes, finish.class
    is Destroyed
  • When you load another scene that
    requres finish.class, it is created
    again and maxScore is assigned to 3
    (once again)

If you want data to persist between scene changes you need to make those classes a “Singleton”.

A very convenient way to achieve this is to make a class with the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {

    private static T instance;

    public static T Instance {
        get {
            T obj = FindObjectOfType<T>();

            if (instance == null) {
                instance = obj;
            } else if (instance != obj) {
            return instance;

Now instead of finish.class extending MonoBehavior, make it extend the Singleton.

public class finish : Singleton<finish>{

Your variable will not be destroyed and replaced when you switch scenes.
Remember to only make classes a “Singleton” if they are unique.

Good singleton classes are GameManagers, PlayerInventory, SceneManagers, or stuff like Appendixes. All stuff that should be static.

okay first you must to build scenes and you know, then you can declare script in other scenes ,or another solve to create game object in scene 1 and add script to it ,and use (dont destroy on load) .