Check Start Problem

Hello Everybody,

I need your little help. I have a script I would check around the character and i found the closest enemy with this script. This script working good but this script check only closest enemy when character is spawn how can i check it everytime ? Example how can i check my radius when my chracter is walking

My Code is here ;

    private var startPoint: ClosestEnemySystem;
    function Start(){
    ClosestEnemy();
    startPoint= ClosestEnemy().GetComponent(ClosestEnemySystem);
    //Wonder= ClosestEnemy().GetComponent(ClosestWonderSystem);
    startPoint.isStart=true;
    }
    
    
    function ClosestEnemy() : GameObject {
    
    var gos : GameObject[];
    gos = GameObject.FindGameObjectsWithTag("Soldier");
    var closest : GameObject;
    //var distance = Mathf.Infinity;
    var distance : float;
    distance = 30;
    
    var position = transform.position;
    
    for (var go : GameObject in gos) {
    var diff = (go.transform.position - position);
    var curDistance = diff.sqrMagnitude;
    if (curDistance < distance) {
    closest = go;
    distance = curDistance;
    }
    }
    return closest;
    } 
    function OnDrawGizmos () {
    if (startPoint != null)
    {
    Gizmos.color = Color.red;
    Gizmos.DrawLine (transform.position, startPoint.gameObject.transform.position);
    }
    }

The Update() method fires every frame. You could also place the ClosestEnemy() call wherever your walking script is.

Hello FizixMan,

Thank you for your reply your mean is ;

    function Update(){
    ClosestEnemy();
    startPoint= ClosestEnemy().GetComponent(ClosestEnemySystem);
    //Wonder= ClosestEnemy().GetComponent(ClosestWonderSystem);
    startPoint.isStart=true;
    }

Yeah pretty much. Though you may want to think about performance and behaviour as it fires every frame.

Well, you can call ClosestEnemy() every 5 seconds; you only need a counter where to store the sum of Time.DeltaTime() until get 5 seconds (or 1 second; it will be best than call ClosestEnemy() for each update).

Hello Kokuma and FizixMan,

Thank you for your reply? How can i use Time.DeltaTime() ?

can you help me ?

Regards

Time.deltaTime is the amount of time (in seconds I believe) that passed between each frame. The idea is since the framerate is not constant (could slow down due to system performance) any movement or rotations (or other various actions) should base themselves upon the time between frames.

For example, if your object’s speed is 10 units per second, you don’t want to move it 10 units each time Update() is called. Rather you would want to multiply its speed (10) against Time.deltaTime (say 1/60th of a second) to find out how much it moved since the last time Update() was called.

So you could keep adding up Time.deltaTime until you hit 5 seconds then run your enemy checking script. (although, to be honest there must be a better way than this, but I personally despise the yield and WaitForSeconds methods.)