unity3d: 4. Countdown of time

in #unity3e7 years ago

Hi! I will show you today, how to make timing in unity3d. It is really simple, it’s issue few lines. We will can calling button function only each three second. Look on the code below.


using UnityEngine;
using System.Collections;
 
public class button : MonoBehaviour {
 
	public float wait=3f;
	public float timing=0f; 
 
	void Update () {
		timing += Time.deltaTime;
 
		if (Input.GetKey (KeyCode.N) && timing >= wait) {
			Debug.Log ("All conditions have been correctly performed");
			timing = 0f;
		}
	}
}

 At the beginning we have defined 2 variables, variable “wait” as you probably guess, it define waiting time for us to execute the code in our case we want to be 3 seconds, variable “countdown time” we will counting down the time.

The rest of the script must be in the “Update” function, because the update function is performed every frame, if you have 30 FPS during the game, 30 frames are performed per second, and the “Time.delataTime” function in the line “timing + = Time.deltaTime;” It counts down the time execution of each frame and adds the time of all these frames to the variable “timing”, in this way the “Time.deltaTime” function can count the execution time of each frame.

Then in the if statement, two conditions must be met, the player must press the “N” button and the variable “timing” must be greater than or equal to the variable “wait”, when the conditions are performed, Debug.Log function is performed and the variable “timing” needs to be reset to zero to be able to count down again from the beginning.

Now compile and assign this script to the object you control and after three seconds, when you press the “N” button, the console displays the message “All conditions have been done correctly“. Variables “timing” and “wait” are set to “public” so during the game you will see in the interface of the unit in the “timing” field that actually the time is counted down.

This content also you can find on my blog devman.pl: http://devman.pl/additions/unity3d-4-timing/

If you recognise it as useful, share it with others so that others can also use it and leave upvote and follow if you wait for next articles :) . 

That’s it for today, see you !!!!! 

Coin Marketplace

STEEM 0.20
TRX 0.15
JST 0.029
BTC 63396.80
ETH 2615.51
USDT 1.00
SBD 2.86