What I’m trying to do is simple. If a collision occurs within 3 seconds after the game starts, reset the timer value and let the game continue. If there’s no collision, call the ResetPrisms method. When I run the following code, numbers like 3.00045 or 3.00611 are printed in the Console area, and the ResetPrisms method is called. In fact, there’s a collision almost every second. However, the code I wrote calls the ResetPrisms method 3 seconds after the game starts, regardless of whether there’s a collision or not. I actually know the reason for this. The most likely reason is that the collision is not perfectly synchronized with the FixedUpdate (or Update, I’ve tried both) calls. So, even if the timer value is reset every time there’s a collision, the timer value may have already exceeded 3 in the next call of the FixedUpdate function. Therefore, the ResetPrisms function is called not at every collision, but only in the FixedUpdate call where the 3-second period has elapsed. However, I don’t know what I can do as a solution. As a beginner, I think this kind of situation is very common, but I couldn’t solve it with artificial intelligence or other tools. The code is as follows. Thank you in advance for your help.
public float waitTime = 3f;
private float timer = 0f;
private bool isCounting = false;
void Update() //I tried FixedUpdate.
{
if (isCounting)
{
timer += Time.deltaTime; //I tried fixedDeltaTime.
if (timer >= waitTime)
{
Debug.Log("timer value: " + timer);
isCounting = false;
timer = 0f; // I tried to remove this line.
ResetPrisms();
}
}
}
void OnCollisionEnter(Collision collision)
{
//I tried to some condition with tags.
timer = 0f;
isCounting = true;
}