[Solved]Stuck between two if Statements loop

So I have a script that changes the scene between 2 scenes
every 50 points but the script doesn’t work as intended and it constantly changes between the 2 scenes non stop and I don’t know how to fix it.

The script:

using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{

    public int TScore = 50 ;

   

    private void Awake()
    {
        PlayerPrefs.GetInt("Tscore");
    }

    public void Update()
    {
        Scene currentScene = SceneManager.GetActiveScene();
        string sceneName = currentScene.name;
        PlayerPrefs.SetInt("Tscore", TScore);

        if (PlayerPrefs.GetInt("ScoreNow") == PlayerPrefs.GetInt("Tscore"))
        {
            
            

             if (sceneName == "first" )
             {
                SceneManager.LoadSceneAsync("second");
             }

            if (sceneName == "second")
            { 
                SceneManager.LoadSceneAsync("first");
            }
            TScore += 50;

        }

    }

}

The two if Statement execute one after the another.

I’m assuming that this script is in both scenes. I imagine what is happening is:

  • As soon as “ScoreNow” hits 50, the game starts loading the other scene. Tscore and “TScore” are incremented by 50 on the next Update()
  • However, when the new scene is loaded, it is using a new instance of GameManager. Tscore is set back to 50 on line 4. Thus, when you hit the Update() loop, “ScoreNow” hasn’t changed, “Tscore” is set to 50, and it’s already time to switch scenes.
  • Repeat

You have two options for fixing this problem:

1. Singleton Game Manager

Because I imagine there will be more data in the Game Manager that you don’t want to reset between scenes, you should adopt a singleton Game Manager design. Include the DontDestroyOnLoad() function in the Game Manager and make sure no scene other than your starting scene has a Game Manager in it.

2. Modify existing code

- Change line 4 to ` public int TScore ; `. If every scene has a game manager, you don't want to be hardcoding the initial value of TScore.
  • Change line 10 to TScore = PlayerPrefs.GetInt("Tscore"); The current line 10 isn’t doing anything.

  • Move line 34 (TScore += 50;) to immediately after line 20, and move line 17 (PlayerPrefs.SetInt("Tscore", TScore);) to immediately after that line. You don’t need to constantly set the value of “TScore” if TScore isn’t changing. In addition, you avoid any possibility that the next scene loads before “TScore” is updated.