I was wondering if someone can help me with my Waypoint script which runs as soon as my game starts, But i dont want it to start immediately when the game runs, i want it to start after a few seconds. So my question is how can i do this, Could i use yield WaitForSeconds? If so how and where do i add this in my script. I’ve searched the forums for about a week now, but couldn’t find anything to get it to work with my script.
Help would be greatly appreciated.
This is my Waypoint script attached to a model:
var waypoint : Transform[];
var speed : float = 20;
private var currentWaypoint : int;
function Update ()
{
if(currentWaypoint < waypoint.length)
{
var target : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = target - transform.position;
var velocity = rigidbody.velocity;
if(moveDirection.magnitude < 1.0)
{
currentWaypoint++;
}
else
{
velocity = moveDirection.normalized * speed;
}
}
rigidbody.velocity = velocity;
RotateTowards();
}
function RotateTowards ()
{
var target : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = target - transform.position;
while(Vector3.Distance(target, transform.position) >= 1.5)
{
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(moveDirection), 0.5* Time.deltaTime);
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
yield;
}
}
The difficulty relies in the fact that a “wait” cannot be used in an Update function.
You can solve this problem using a “locking” mechanism, as in the implementation below:
var lock = true;
var my_time = 3; //I suppose 3 seconds
function Start(){
yield WaitForSeconds(my_time);
lock = false;
}
function Update(){
if (!lock){
//Here, you put all what you actually have in your update function
//(just remove the final "yield")
}
}
When the game starts, you wait 3 seconds (but you can adjust this parameter, it’s just an example). After this time passed, you deactivate the lock.
Do you see the Update function now? It works only if the lock is deactivated!