Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Awilt002 · Nov 23, 2016 at 02:47 PM · timertimer countdowntimer-script

Creating a timer that starts when my 3rd scene is loaded

I am wanting to create a timer that will start counting down from 10 when my 3rd scene (Second Level) is loaded, then when this reaches 0 the player dies, re-spawns at the beginning of the level and then this countdown repeats itself.

I currently have that when the timer reaches 0 the player re-spawns in the correct place, but this is used using an if statement saying that if the timer is greater than or equal to 10 then to make the player position equal to the way-point, this causes problems after 10 seconds since the position is then updating every frame to that one position and my player then cannot move.

My Timer code is as below:

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

public class Timer : MonoBehaviour { float gameDuration = 10; bool endGame = false; private GameManager GameManager; private SetSpawn SetSpawn; private PlayerManager PlayerManager; public GameObject Player; private GameObject Waypoint; public Text timeDisplay;

 // Use this for initialization
 void Start () {
     GameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
     SetSpawn= GameObject.Find("Waypoint").GetComponent<SetSpawn>();
     PlayerManager = GameObject.Find("Player").GetComponent<PlayerManager>();
 }
 
 // Update is called once per frame
 void Update () {
     if (Time.time >= gameDuration)
     {
         endGame = true;
     }
     if (endGame == true)
     {

         Player.transform.position = Player.GetComponent<PlayerManager>().spawnPoint;
         GameManager.deaths = GameManager.deaths++;
         print("Respawn");
         
     }
     else
     {
         float timeLeft = Mathf.RoundToInt(gameDuration - Time.time);
         timeDisplay.text = " You have " + timeLeft.ToString() + " seconds!";
     }
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by SarfaraazAlladin · Nov 23, 2016 at 09:58 PM

You should look into coroutines for something like this :)

Once you know how to use them, you'll find that coroutines are a great way to avoid Update, but still get frame by frame control.

In this case, however, they offer an awesome method called WaitForSeconds();

     void Start () 
     {
         GameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
         SetSpawn= GameObject.Find("Waypoint").GetComponent<SetSpawn>();
         PlayerManager = GameObject.Find("Player").GetComponent<PlayerManager>();
 
         //Start the co routine
         StartCoroutine("DeathTimer");
     }
     
     IEnumerator DeathTimer()
     {
         //wait 10 seconds...
         yield return new WaitForSeconds (10);
 
         RespawnPlayer ();
     }
 
     void RespawnPlayer()
     {
         Player.transform.position = Player.GetComponent<PlayerManager>().spawnPoint;
         GameManager.deaths = GameManager.deaths++;
         print("Respawn");
     }

And that should do it!

You'll notice that coroutines can't be called the same way as a normal method, and you'll have to use StartCoroutine(); instead.

There is a bunch to learn on the topic, but well worth your time if you google coroutines. Like I said before, you can also make a loop inside of one that will run every frame until you decide to break out of it, which is great for smaller animations or timers that would otherwise clutter up the Update loop.

Hope this helps!

EDIT

If you want to have the respawn happen in a loop, look into while loops. Here's a simple example

     void Start () 
     {
         GameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
         SetSpawn= GameObject.Find("Waypoint").GetComponent<SetSpawn>();
         PlayerManager = GameObject.Find("Player").GetComponent<PlayerManager>();
 
         //Start the co routine
         StartCoroutine("DeathTimer");
     }
     
     IEnumerator DeathTimer()
     {
         bool stay = true;
         while (stay) 
         {
             if(/* whatever condition you want to exit while loop */)
             {
                 stay = false;
                             break;
             }
 
             //wait 10 seconds...
             yield return new WaitForSeconds (10);
             RespawnPlayer ();
         }
     }
 
     void RespawnPlayer()
     {
         Player.transform.position = Player.GetComponent<PlayerManager>().spawnPoint;
         GameManager.deaths = GameManager.deaths++;
         print("Respawn");
     }

While statements are useful, but beware the infinite loop. Always make sure you have the proper logic setup to break out of your loops.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Awilt002 · Nov 24, 2016 at 02:47 PM 0
Share

That's absolutely great thank you :D

I was hoping though that the coroutine would then restart and wait another 10 seconds before running the Respawn function again,

The level this code is running on is a timed level that you have 10 seconds to finish, if you don't then the respawn function runs, which I want it to do every 10 seconds until the player finishes the level.

Thank you for showing me coroutines though, I'm going to go research them now. ($$anonymous$$y lecturer has literally just said we're researching this now)

Thank you once again :D

avatar image SarfaraazAlladin Awilt002 · Nov 24, 2016 at 07:12 PM 0
Share

I updated my answer with a second example to show how you can use a while loop to get the control you need. If you like my answer, I would be grateful if you marked it as correct :)

Have fun learning co routines

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

80 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

I need a "loop" timer that disables a action until the timer resets. 0 Answers

Help with a timer 1 Answer

How to get left time from countdown to point? 0 Answers

Hi there. i´m new to unity and i´m building a labyrinth. my question is how to add a timer countdown? 1 Answer

My countdown timer doesn't work,I'm trying to create a countdown timer 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges