Since C# is being pretty cringe, I am asking for help on how to debug it based on the comments in the code. As a summary, I have a timer running in console (noob here, code copy-pasted or tutorial'd) and the numbers ONE and GO are running simultaneously, and I have not found a way to stop the timer after the intended result is reached, and help would be appreciated!
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public int startTime = 4;
void Start()
{
InvokeRepeating("timer", 1.0f, 1.0f);
}
void timer()
{
if (startTime > 0)
{
if (startTime == 3)
{
Debug.Log("THREE");
startTime -= 1;
}
else
{
if (startTime == 2)
{
Debug.Log("TWO");
startTime -= 1;
}
else
{
Debug.Log("ONE");
startTime -= 1;
//Precent "ONE" and "GO!" from running simultaneously
}
}
}
if (startTime == 0)
{
Debug.Log("GO!");
//Fix "GO!" playing to console indefinetly after timer is finished
}
void Update()
{
}
}
}
CodePudding user response:
i think you want //if (startTime == 0) else { Debug.Log("GO!"); //Fix "GO!" playing to console indefinetly after timer is finished }
CodePudding user response:
To do this, you can use the CancelInvoke method by passing the method name to quotes as a parameter you can call it when startTime goes to 0. You can safly remove the Update Method
public int startTime = 3;
void Start()
{
InvokeRepeating("timer", 1.0f, 1.0f);
}
void timer()
{
//go throw all the cases
switch (startTime)
{
case 0:
Debug.Log("GO!");
CancelInvoke("timer");
break;
case 1:
Debug.Log("ONE");
break;
case 2:
Debug.Log("TWO");
break;
case 3:
Debug.Log("THREE");
break;
}
//substract - from time
startTime -= 1;
}
Or use this Coroutine
void Start()
{
StartCoroutine("timer");
}
IEnumerator timer()
{
//debug the time
Debug.Log(startTime); //you can use the if statement do show it as text or use any humanizer **C# 101 series**
startTime--; //here we substract 1 from time
//we wait for 1s
yield return new WaitForSeconds(1);
//if the time still >= 0 repeat
if(startTime >=0)
StartCoroutine("timer");
}