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 Grey_Wolf9 · Nov 18, 2019 at 12:31 AM · unity 2dplayer movementtimer countdowntimer-script

Using a timer in conjunction with two push buttons from Arduino input

Hello all, noob here

So I am using two push buttons (connected to an Arduino Uno) as an input to my game. The player has to push down both buttons at the same time for the character to move in the game. I want the player to hold down the buttons for a different amount of time in each level. I have a working Arduino and a working Unity timer and player script, but am not able to get the code to do what I want. What I basically want is that only when the player presses the buttons down, does the timer start counting down. Right now, the timer starts as soon as the scene begins. I know that I somehow have to reference the timer script to the button object, I have tried this but it still doesn't work. Note that the timer UI does have a Timer tag on it. Right now, the timer just doesn't count down at all. Please help

Timer script:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 
 public class Timer : MonoBehaviour
     {
         public int timeLeft;
         public Text countdownText;
         private bool timerStarted;
 
     public void BeginTimer()
     {
 
     }
 
     public void BeginTimer(int seconds) 
         {
         // Here you have to decide whether you want to restart a timer
 
         timeLeft = seconds;
         // or if you rather want to continue counting down
         if (!timerStarted)
         {
             timeLeft = seconds;
 
             StartCoroutine(LoseTime());
         }
         }
 
         public void StopTimer()
         {
             StopAllCoroutines();
         }
     void Update()
     {
         countdownText.text = ("Time Left = " + timeLeft);
 
         if (timeLeft <= 0)
         {
 
             Invoke("ChangeLevel", 0.1f);
         }
     }
 
         private IEnumerator LoseTime()
         {
             timerStarted = true;
         
 
         while (true)
             {
                 yield return new WaitForSeconds(1);
                 timeLeft--;
             //countdownText.text = ("Time Left = " + timeLeft);
             //countdownText.text = $"Time Left = {timeLeft}";
         }
 
         //Invoke("ChangeLevel", 0.1f);
         //Invoke(nameof(ChangeLevel), 0.1f);
         }
 
         void ChangeLevel()
         {
             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
         }
     }

Player script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.IO.Ports;
 using UnityEngine.UI;
 
 public class PlayerController : MonoBehaviour
 {
     public float Speed;
     public Vector2 height;
     public float xMax, xMin, yMin, yMax;
     public bool buttonPressed = false;
 
     public Rigidbody2D Character;
     public Timer timer;
     public Rigidbody2D _rigidbody;
 
     private SerialPort sp = new SerialPort("\\\\.\\COM4", 9600);
 
     private void Awake()
     {
         FetchReferences();
     }
 
     [ContextMenu("FetchReferences")]
     private void FetchReferences()
     {
         if (!Character) Character = GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>();
         if (!timer) timer = GameObject.Find("Timer").GetComponent<Timer>();
     }
 
     private void Start()
     {
         if (!sp.IsOpen)
         {
             sp.Open(); // Open 
         }
         sp.ReadTimeout = 1;
     }
 
     private void Update()
     {
        if (sp.IsOpen)
         {
             try
             {
 
                 string value = sp.ReadLine(); //Read the information
                 int button = int.Parse(value);
 
                 if (button == 0) //*Input.GetKeyDown(KeyCode.Space*/)  //jump
                 {
                     buttonPressed = true;
 
                     Character.GetComponent<Rigidbody2D>().AddForce(height, ForceMode2D.Impulse);
 
                     
 
                     timer.BeginTimer();
                 }
                 else
                 {
                     
                     timer.StopTimer();
                 }
             }
             catch (System.Exception)
             {
                
             }
         }
     }
 
 
     private void FixedUpdate()
     {
         Character.position = new Vector3
                     (
                         Mathf.Clamp(GetComponent<Rigidbody2D>().position.x, xMin, xMax),
                         Mathf.Clamp(GetComponent<Rigidbody2D>().position.y, yMin, yMax)
                     );
         //Character.position = new Vector3(Mathf.Clamp(Character.position.x, Min.x, Max.x), Mathf.Clamp(Character.position.y, Min.y, Max.y));
     }
 
     
     private void ApplicationQuit()
     {
         if (sp != null)
         {
             {
                 sp.Close();
             }
         }
     }
 }





Please assist; no errors this far

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
0

Answer by $$anonymous$$ · Nov 18, 2019 at 05:39 AM

im not gonna read your code.
my brain hurts when i read my own code.
but what I understood from you question
im gonna say

you want timer to keep time, that can only happen in update function.
but you want timer to start only when user presses a button, so all you need is a bool

 when bool is true, do the timer  
 when button is pressed bool is true  

that way timer will not start as soon as scene start.

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 Grey_Wolf9 · Nov 18, 2019 at 01:33 PM 0
Share

@nanavatidhruvik Thank you for your reply. Where would I put the bool function: in the timer script or in the player script? I know this may sound like silly questions but I have been stuck with this problem for quite some time now and I really don' t know how to go about doing it

avatar image $$anonymous$$ Grey_Wolf9 · Nov 21, 2019 at 06:35 PM 0
Share

bool before timer

  private void Update()  
  {  
      if (StartTimer == true)  
          {  
              //do the timer thing  
          }  
   }
   public void ButtonPress()  
   {  
           StartTimer = true;  
    }
avatar image Grey_Wolf9 $$anonymous$$ · Nov 21, 2019 at 09:25 PM 0
Share

@nanavatidhruvik I tried implementing your suggestion, but it didn't work: I was probably doing something wrong. So I tried referencing the timer script in the player script after the button is pressed and it still doesn't work. There aren't any errors but the timer just doesn't count down now.

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

118 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

Related Questions

countdown timer starts from the begining when i reLaunch the app 1 Answer

How to make 2D Player dash towards mouse position in a straight line? 1 Answer

Changing font color in timer script (js) 0 Answers

How do you make a countdown timer that will lose time if you press a button? 1 Answer

Timer Continues After Object is disabled 2 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