- Home /
How to make a cooldown on a script
Hello People, I Have a script for a pretty nice teleport but the issue I'm having is that there is no cool down so if i can repeatedly press teleport and it will.. I Would like to add a 10second cool down for this spell but I'm afraid i do not have the knowledge on adding a cool down or what system is needed to achieve this. Here is the script so people can see it and hopefully help me out on this issue. Thank you!
var teleportSound: AudioClip; // assign the sound in the Inspector
var distance: float = 20;
function Update(){
if (Input.GetKeyDown("t")){
var dest = transform.position + transform.forward * distance;
var hit: RaycastHit;
// if some obstacle between player and dest...
if (Physics.Linecast(transform.position, dest, hit)){
// set dest to 1.5m before the obstacle
dest = transform.position + transform.forward * (hit.distance - 1.5);
}
dest.y = 1000; // choose a really high spot to do the raycast
if (Physics.Raycast(dest, -Vector3.up, hit)){ // if there's ground below the destination point...
dest = hit.point; // define the destination somewhat above the hit.point
dest.y += 2; // to make the character fall to the ground
transform.position = dest;
audio.PlayOneShot(teleportSound);
}
}
}
So if anyone could give me some information on this or maybe point me in the correct direction i would be more then appreciative. Thank you for you time reading this. :)
you just need the Invoke() command. it's the simplest way to do timers and the like in Unity.
so it would be something like
var disableTeleportAtThe$$anonymous$$oment:boolean
teleport function would look like this...
if ( disableTeleportAtThe$$anonymous$$oment ) return;
teleport code
disableTeleportAtThe$$anonymous$$oment = true
Invoke( "teleportO$$anonymous$$Again", 10.0 );
function teleportO$$anonymous$$Again()
disableTeleportAtThe$$anonymous$$oment = false;
ok ?
Answer by well_played_mike · Oct 11, 2012 at 08:22 AM
You can add one more condition in your if statement, so it's something like this :
var nextTeleport;
var duration = 2.0;
if (Input.GetKeyDown("t") && Time.time > nextTeleport){
nextTeleport = Time.time + duration;
var dest = transform.position + transform.forward * distance;
For more information please look into Time.time documentation.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
how to add a sound to this script 3 Answers
Teleport enemy after player collides with an object? 0 Answers
How to toggle a key for a car to go forward or backward? 1 Answer
Error whit c# code 'UnityEngine.Transform.position' because it is not a variable. 1 Answer