- Home /
how to only allow a script to run once every X amount of given time unity
I'm new to unity and coding in general here is my code so far. I'm not sure whats wrong if i could get some help that would be great. i'm trying to make a 2d strategy game where I can move once within the space of 5 seconds. the script is called PlayerController.
#pragma strict
var ph : PlayerController;
private var speed = 10;
private var pos : Vector3;
private var tr : Transform;
function Start()
{
pos = transform.position;
tr = transform;
ph = GetComponent(PlayerController);
ph.enabled = false;
}
function Update()
{
if (Input.GetKey(KeyCode.D) && tr.position == pos)
{
pos += Vector3.right;
}
else if (Input.GetKey(KeyCode.A) && tr.position == pos)
{
pos += Vector3.left;
}
else if (Input.GetKey(KeyCode.W) && tr.position == pos)
{
pos += Vector3.up;
}
else if (Input.GetKey(KeyCode.S) && tr.position == pos)
{
pos += Vector3.down;
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
function OnlyMoveOnce(runTime : float) {
var timer = 5;
while (timer < runTime) {
ph.enabled = true;
timer += Time.deltaTime;
yield;
}
}
Answer by tormentoarmagedoom · Oct 02, 2017 at 11:03 AM
Good day @dragonballcreed !!
I recommend you to create a bool variable called "CanMove". To allow movement, CanMove must be true. When the player executes a movement, this CanMove variable becomes false, and activate a timer for 5 seconds. When the timer reaches 5 seconds the CanMove variable becomes true again.
To make a timer you need Time.deltaTime. You can use this code (is in C#, but I'm sure you will understand it) :
void Update()
{
private float MovementTimer = 0;
private float MaxTimeForNextMove = 5;
if(CanMove == false && MovementTimer < MaxTimeForNextMove )
{
MovementTimer += Time.deltaTime
}
if (MovementTimer >= MaxTimeForNextMove )
{
CanMove = true;
MovementTimer = 0;
}
This way, the timer will start counting when you change the CanMove variable to false. When the timer reaches 5 seconds, it goes 0 again and allow player to move.
Your answer
Follow this Question
Related Questions
2d camera help! 0 Answers
random sprite javascript 0 Answers
How would I make a route that shows where player moves beforehand? 0 Answers
Changing material orientation dependant on mouse location? 0 Answers
2D Smoke or Particle 2 Answers