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
0
Question by mirceaculita · Jul 24, 2017 at 11:04 AM · scripting problem2d gamescripting beginnertimer

Add more seconds to the timer when colliding with an object.

So I am making a 2D game that has a countdown timer in every level. if you get to 0 seconds you lose and the level restarts. Now I want to make an object like a coin lets say that when you collide with it, you receive 5 more seconds.

Here is the script I am using for the timer:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 
 public class countdown : MonoBehaviour {
 
     public string levelToLoad;
     public float timer = 0f;
     private Text timerSeconds;
 
     // Use this for initialization
     void Start () {
 
         timerSeconds = GetComponent<Text> ();
 
     }
     
     // Update is called once per frame
     void Update () {
         
             timer -= Time.deltaTime;
             timerSeconds.text = "Time left = " + timer.ToString ("f2");
             if (timer <= 0.05) {
                 SceneManager.LoadScene (levelToLoad);
             }
 
     }
 }
 

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
Best Answer

Answer by andrew-lukasik · Jul 24, 2017 at 11:51 AM

First of add this code to your countdown class:

 public class countdown : MonoBehaviour
 {
     
     public float timer = 0f;
 
     /// <summary>
     /// This field will contain a reference to a countdown existing in the scene
     /// </summary>
     static countdown _instance;
 
     void Awake ()
     {
         //register this countdown instance:
         _instance = this;
     }
 
     public static void ModifyTimer ( float byAmount )
     {
         _instance.timer += byAmount; 
     }
 }

Create ICollectible.cs file containing this:

 /// <summary>
 /// Interface ICollectible will distinguish collectible objects
 /// </summary>
 public interface ICollectible
 {
     //every class implementing ICollectible must have this method as public:
     void OnCollected ();
 }

Create CollectibleObject.cs and slap this component on all things collectible:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 /// <summary>
 /// Collectible object
 /// </summary>
 [RequireComponent( typeof(Collider2D) )]
 public  class CollectibleObject : MonoBehaviour,ICollectible//<look it's implementing ICollectible
 {
     /// <summary>
     /// Timer delta on collected
     /// </summary>
     public float timerDelta = 10f;
 
     /// <summary>
     /// Implementation code for intereface ICollectible's "OnCollected" method
     /// </summary>
     public void OnCollected ()
     {
         //modify timer:
         countdown.ModifyTimer( timerDelta );
         
         //disable this object:
         gameObject.SetActive(false);
     }
 }

Player.cs, slap this on your player:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 /// <summary>
 /// Player component
 /// </summary>
 [RequireComponent( typeof(Rigidbody2D) )]
 public class Player : MonoBehaviour
 {
 
     void OnCollisionEnter2D ( Collision2D coll )
     {
         //is it ICollectible:
         ICollectible collectible = coll.gameObject.GetComponent<ICollectible>();
         if( collectible!=null )
         {
             //collectible! ( ͡° ͜ʖ ͡°)
             collectible.OnCollected();
         }
         {
             //no collectible!
             //(╯°□°)╯︵ ┻━┻
         }
     }
 
 }
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 SohailBukhari · Jul 24, 2017 at 01:30 PM 0
Share

No need to make static countdown _instance; because we just need $$anonymous$$odifyTimer timer which is already static. he can do whatever in the OnCollected and i think you should not provide this line gameObject.SetActive(false); if he wants to destroy then write his on code.

 public void OnCollected ()
      {
          //modify timer:
          countdown.$$anonymous$$odifyTimer( timerDelta );
          // do more what you want
      }



avatar image andrew-lukasik SohailBukhari · Jul 24, 2017 at 03:02 PM 0
Share

I may be wrong but, in my $$anonymous$$d, making _instance static actually helps limit use of static to this single field. Because otherwise $$anonymous$$odifyTimer cannot access timer field which quickly leads to escalatory use of static (at least as commonly seen in new coders)

avatar image
1

Answer by Oysterino · Jul 24, 2017 at 11:27 AM

try adding something like this:

   private void OnCollisionEnter2D(Collision2D collision)
         {
             if(collision.gameObject.CompareTag("Coin"))
             {
                  timer += 5;
                  Destroy(collision.gameobject);    
             }    
         }

This should add 5 seconds to the timer and remove the Coin when colliding.

So all you Coin-like object need is a Collider and a tag that matches the current "Coin"-tag in the code above.

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 mirceaculita · Jul 24, 2017 at 11:32 AM 0
Share

what I need is to register if the player collides with a coin. I don't think this will work because the timer can't collide with anything.

avatar image SohailBukhari mirceaculita · Jul 24, 2017 at 01:35 PM 0
Share

why timer will collide with anything? he is just asking that check Collision/trigger of player with the gameObject(Coin) and the simply add the timer value. You can add value to timer by just taking reference of the class or making timer value static and OnCollisionEnter just invoke the event and in his listener add the value.

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

120 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 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

(C#) SetActive isn't working on my UI 2 Answers

Collider not registering hits? 4 Answers

Hello can anyone help me in my code i am converting some code JS to C# 1 Answer

Bullets follow the ship in 2D Space Shooter game 2 Answers

Random Select (Scripting Problem) 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