# Check Distance every 5 seconds

I have a noob question and could use a little help

Im using the FixedUpdate so that Im not calling this every frame how would I do it every 5 seconds?

``````// detects when the other transform is closer than closeDistance
// this is faster than using Vector3.magnitude

var thePlayer : Transform;
var thisEnemy : Transform; //current transform data of this enemy
var closeDistance = 5.0;
var rotationSpeed = 3; //speed of turning
var moveSpeed = 3; //move speed

function FixedUpdate()
{
var sqrLen = (thePlayer.position - thisEnemy.position).sqrMagnitude;

// square the distance we compare with
if( sqrLen < closeDistance*closeDistance )
{
print ("The enemy transform is close to me!");
}

//rotate to look at the player
thisEnemy.rotation = Quaternion.Slerp(thisEnemy.rotation,
Quaternion.LookRotation(thePlayer.position - thisEnemy.position), rotationSpeed*Time.deltaTime);

//move towards the player
thisEnemy.position += thisEnemy.forward * moveSpeed * Time.deltaTime;

}
``````

How would you use it?

I tried it like in the link you gave me but it seems like its called every .3 seconds doubling the speed of my enemy soâ€¦ something doesnâ€™t seem right.

Iâ€™ve just found Coroutines so Im going to give that a try yield WaitForSeconds(5.0);

You replace 0.3 with 5â€¦

``````function Start () {
InvokeRepeating ("TheMethod", 5, 5);
}
``````

Maybe I phrased my response wrong

TheMethod is the function the will be called after 5 seconds and repeated every 5 seconds. The problem I now see is that its Doubling the enemies speed because its calling it again and again which is invoking repeating.

``````function Update ()
{
InvokeRepeating ("TheMethod", 5, 5);
}
function TheMethod()
{
//my code from above
}
``````

What Im trying to accomplish is this quote from the scripting reference:

which can be found here:
http://unity3d.com/support/documentation/ScriptReference/index.Performance_Optimization.html

Im just not sure how to do it with my code above

Simple solution, if you donâ€™t want it called every time Update is called, then donâ€™t do it in Update. And most definitely not in FixedUpdate.

Just call it once when you want to start it. Maybe thatâ€™s on object creation in Start, or maybe youâ€™ll just have to create a new function and call it when an event happens.