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 /
avatar image
1
Question by MiloRoban · Apr 05, 2018 at 06:27 PM · 2d-platformertimerrestarttimer-script

How to I get the timer counter to restart when the player hits the ground and respawns?

So I am creating a 2D platformer and the goal is to go as long as possible without dying, and I need to make it so when the player hits the ground, the text displaying the amount of time the player has ran for restarts. I will post the code that I have already written.

Any and all help is greatly appreciated Score Manager Script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 public class ScoreManager : MonoBehaviour
 {
     public Text scoreText;
     public Text hiScoreText;
     public float scoreCount = 0;
     public float hiScoreCount = 0;
     public float pointsPerSecond = 2;
     public bool scoreIncreasing;
     void Update()
     {
         if (scoreIncreasing)
         {
             scoreCount += pointsPerSecond * Time.deltaTime;
         }
         if (scoreCount > hiScoreCount)
         {
             hiScoreCount = scoreCount;
         }
         scoreText.text = "Score: " + Mathf.Round(scoreCount);
         hiScoreText.text = "High Score: " + Mathf.Round(hiScoreCount);
     }
     public void ResetPlayerScore()
     {
         scoreCount = 0;
         scoreText.text = "Score: 0";
         scoreIncreasing = false;
     }
     public void EnableScoring()
     {
         scoreIncreasing = true;
     }
 }
 
 

Caller Script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 public class Caller : MonoBehaviour {
   ScoreManager _sm;
     void Start()
     {
         // Get reference to ScoreManager in scene
         _sm = GameObject.Find("ScoreManager").GetComponent<ScoreManager>();
     }
     private void OnCollisionEnter2D(Collision2D collision)
     {
         if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
         {
             _sm.ResetPlayerScore(); // sample example of calling a method written in your ScoreManager
         }
     }
     private void OnCollisionExit2D(Collision2D collision)
     {
         if (collision.gameObject.layer == LayerMask.NameToLayer("Player"))
         {
             _sm.EnableScoring();
         }
     }
 }
 
 


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

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by melsy · Apr 05, 2018 at 11:59 PM

I canhed this post to rewrite your two classes a little cleaner and commented them pretty well to help you understand.

 using UnityEngine;
 using UnityEngine.UI;
 
 public class ScoreManager : MonoBehaviour
 {
     // SerializeField is a way to see the privae variable in the inspector. 
     // When coding it is a good idea to not let a variable be accessed by anything that
     // it doesn't need to be.  If it is only used in this class it should be private. 
     [SerializeField]
     Text scoreText;
     [SerializeField]
     Text hiScoreText;
     [SerializeField]
     float scoreCount = 0;
     [SerializeField]
     float hiScoreCount = 0;
     [SerializeField]
     float pointsPerSecond = 2;
    
     // Assign the player to this in the inspector. 
     [SerializeField]
     SimplePlatformScript player;
     const string sScore = "Score: ";
     const string sHighScore = "High Score: ";
 
     void Update()
     {
         if (scoreIncreasing)
             scoreCount += pointsPerSecond * Time.deltaTime;
 
         if (scoreCount > hiScoreCount)
         {
             hiScoreCount = scoreCount;
             // The high score only needs to be updated when the score is higher. Not every frame. 
             UpdateHighScoreText();
         }
         UpdateScoreText();
     }
 
     public void ResetPlayerScore()
     {
         scoreCount = 0;
         scoreText.text = "Score: 0";
      }
            
     void UpdateScoreText()
     {
         scoreText.text = string.Format("{0} {1}", sScore, Mathf.Round(scoreCount));
     }
 
     void UpdateHighScoreText()
     {
         hiScoreText.text = string.Format("{0} {1}", sHighScore, Mathf.Round(hiScoreCount));
     }
 }
 
 public class SimplePlatformScript : MonoBehaviour
 {
     //[HideInInspector] public bool facingRight = true;
     [HideInInspector] public bool jump = false;
     //public float moveForce = 365f;
     //public float maxSpeed = 5f;
     public float jumpForce = 1000f;
 
     public Transform groundCheck;
     // Store the layer in this reference so it doesnt have to create a new reference 
     // every physics frame.
     [SerializeField]
     LayerMask whatIsGround;
 
     // Changed this to a public so the ScoreManager can see it. 
     [SerializeField]
     public bool grounded = false;
 
     //private Animator anim;
     private Rigidbody2D rb2d;
     // Use const string anytime you are calling a string more than once. 
     // Everytime you call a literal string it puts a new one in memory.  
     // Doing it like this make it only create one. 
     const string sJump = "Jump";
     // Use this for initialization
     void Awake()
     {
         //anim = GetComponent<Animator>();
         rb2d = GetComponent<Rigidbody2D>();
     }
 
     void Update()
     {
         if (Input.GetButtonDown(sJump) && grounded)
         {
             // This is ok to do in update as it feels better to the player. 
             // This is a physics action but doing an input actions
             // feels off to the player if there is a delay. 
             rb2d.AddForce(new Vector2(0f, jumpForce));
         }
     }
 
     void FixedUpdate()
     {
         // Any physics calculations are better done in the FixedUpdate. 
         grounded = Physics2D.Linecast(transform.position, groundCheck.position, whatIsGround);
     }
 }
Comment
Add comment · Show 3 · 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 MiloRoban · Apr 06, 2018 at 06:06 PM 0
Share
  public class SimplePlatformScript : $$anonymous$$onoBehaviour
  {
  
      //[HideInInspector] public bool facingRight = true;
      [HideInInspector] public bool jump = false;
      //public float moveForce = 365f;
      //public float maxSpeed = 5f;
      public float jumpForce = 1000f;
      public Transform groundCheck;
  
  
      private bool grounded = false;
      //private Animator anim;
      private Rigidbody2D rb2d;
  
  
      // Use this for initialization
      void Awake()
      {
          //anim = GetComponent<Animator>();
          rb2d = GetComponent<Rigidbody2D>();
      }
  
      // Update is called once per frame
      void Update()
      {
          grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << Layer$$anonymous$$ask.NameToLayer("Ground"));
  
          if (Input.GetButtonDown("Jump") && grounded)
          {
              jump = true;
          }
      }
  
      void FixedUpdate()
      {
          if (jump)
          {
              //anim.SetTrigger("Jump");
              rb2d.AddForce(new Vector2(0f, jumpForce));
              jump = false;
  
          }
      }
  }
avatar image MiloRoban · Apr 07, 2018 at 08:16 PM 1
Share

I am getting some compiler errors that I cannot seem to decipher.

Assertion failed: Assertion failed on expression: 'm_CurrentEntriesPtr != NULL && m_IsGettingEntries'

UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Assertion failed: Assertion failed on expression: 'm_CurrentEntriesPtr != NULL && m_IsGettingEntries'

UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Assets/Scripts/Caller.cs(26,17): error CS1061: Type Score$$anonymous$$anager' does not contain a definition for EnableScoring' and no extension method EnableScoring' of type Score$$anonymous$$anager' could be found. Are you missing an assembly reference? Assets/Scripts/Score$$anonymous$$anager.cs(28,13): error CS0103: The name `scoreIncreasing' does not exist in the current context

avatar image MiloRoban · Apr 08, 2018 at 04:56 PM 0
Share

Where you able to see what the errors where?

avatar image
1

Answer by MiloRoban · Apr 06, 2018 at 02:28 AM

This is my player jump script. using UnityEngine; using System.Collections;

 public class SimplePlatformScript : MonoBehaviour
 {
 
     //[HideInInspector] public bool facingRight = true;
     [HideInInspector] public bool jump = false;
     //public float moveForce = 365f;
     //public float maxSpeed = 5f;
     public float jumpForce = 1000f;
     public Transform groundCheck;
 
 
     private bool grounded = false;
     //private Animator anim;
     private Rigidbody2D rb2d;
 
 
     // Use this for initialization
     void Awake()
     {
         //anim = GetComponent<Animator>();
         rb2d = GetComponent<Rigidbody2D>();
     }
 
     // Update is called once per frame
     void Update()
     {
         grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
 
         if (Input.GetButtonDown("Jump") && grounded)
         {
             jump = true;
         }
     }
 
     void FixedUpdate()
     {
         if (jump)
         {
             //anim.SetTrigger("Jump");
             rb2d.AddForce(new Vector2(0f, jumpForce));
             jump = false;
 
         }
     }
 }
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 melsy · Apr 06, 2018 at 03:50 AM 1
Share

make this a comment to my answer. That is exactly what i thought it would look like. Change my PlayerScript to yours, Then make your grounded bool public , you can use the attribute [HideInInspector] above it if you want to not show it in the inspector. Put my stuff inside the score$$anonymous$$anager and all should work perfect.

avatar image MiloRoban melsy · Apr 06, 2018 at 06:10 PM 0
Share

Excuse my incompetence, but what do you mean by changing your PlayerScript to $$anonymous$$e?

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

83 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 avatar image avatar image avatar image

Related Questions

Timer jitters? SOLVED 0 Answers

timer not ticking down 2 Answers

How to restart a level with countdown? 4 Answers

How to manipulate time in unity? 1 Answer

How to give points after certain number of seconds?,How to give points after a certain number of seconds? 1 Answer


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