Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Trying to change scene when score hits a certain value

Discussion in 'Scripting' started by robert2251, Feb 28, 2020.

  1. robert2251

    robert2251

    Joined:
    Nov 27, 2018
    Posts:
    15
    Putting the code in update works perfectly, but I put it in Coroutine so that I can make it wait 3 seconds before the scene changes, it's not working. Once the score reaches 530 the game just stays there. Any help would be amazing, thanks!
    Code (CSharp):
    1. public class Score : MonoBehaviour
    2. {
    3.     public static int scoreValue = 0;
    4.     Text score;
    5.     // Start is called before the first frame update
    6.     void Start()
    7.     {
    8.         score = GetComponent<Text>();
    9.         scoreValue = 0;
    10.         StartCoroutine(LevelUpdater());
    11.     }
    12.  
    13.     // Update is called once per frame
    14.     void Update()
    15.     {
    16.         score.text = "Score: " + scoreValue;
    17.     }
    18.  
    19.     IEnumerator LevelUpdater()
    20.     {
    21.         if (scoreValue == 530)
    22.         {
    23.             yield return new WaitForSeconds(3);
    24.             Application.LoadLevel("Start");
    25.         }
    26.     }
    27. }
     
  2. VSMGames

    VSMGames

    Joined:
    Jan 12, 2020
    Posts:
    47
    You are starting your coroutine in your start function. At the moment you have to reach 530 points in 3 seconds for this to work. Instead move your if statement into update function and start the coroutine when the 530 points is reached. Also you can create a bool which checks true if the score is reached, this way you can use it to stop the game and make sure the coroutine is started only once not on every frame.

    Edit: I have to correct myself, the part about the 530 points in 3 seconds in my post was wrong. You have to have 530 points when your game starts not in 3 seconds for your present code to work. My bad :)
     
    Last edited: Feb 28, 2020
  3. robert2251

    robert2251

    Joined:
    Nov 27, 2018
    Posts:
    15
    I'll test it out in about an hour, thanks a lot!
     
  4. robert2251

    robert2251

    Joined:
    Nov 27, 2018
    Posts:
    15
    It worked, tyvm!