- Home /
How to call a method once inside fixed update
Hey guys, I am trying to set a units pathing position to another unit if they are within a certain distance to each other. The problem is that my distance detection is in fixedUpdate method, and if I want to change the path he is on I have to do it here too. When I do this, it repeatedly adds the new waypoint for the unit to travel, and eats up my memory like crazy. I am wanting to know if there is a way to call my pathing waypoint just once, or maybe even like once every few seconds. Thanks guys,
public void Start () {
CreateBehavior (); //determines whether the unit goes to a tower or the base
FindCloseUnits (); //finds all the player controlled units on the map and adds them to a list
seeker = GetComponent<Seeker>();
controller = GetComponent<CharacterController>();
//behavior code conditions
GameObject towerObject = GameObject.Find("Cylinder");
Tower towerCaptureObject = towerObject.GetComponent<Tower>();
seeker.StartPath (transform.position, targetPosition, OnPathComplete); //makes the path the unit follows
}
public void LocalAvoidance(){ //do the distance of specific vectors like x,z to determine direction unit is pushed back
for (int i=0; i<UnitsList.Count; i++) { //this iterates through my list of unit objects
float distance = Vector3.Distance (transform.position, UnitsList[i].transform.position);
//this calculates the distance from one unit to another
if (distance <= 5) { //if the distance is less than 1.5 push the unit away
targetPosition = UnitsList[i].transform.position;
seeker.StartPath (transform.position, targetPosition, OnPathComplete); //makes the path the unit follows
//this is where it buggs out and eats all my memory. I need the seeker.startpath function to be called only once with the new target position unless the other unit changes positon, then it will get his position... } }
}
Not sure I understand, but if your problem is that something is being called repeatedly in FixedUpdate and you want to make it call just once, you could use a boolean switch. Say in FixedUpdate to only call it when the boolean is true, then once you call it set it to false.
As for every few seconds, you could make a coroutine that sets it to true every few seconds.
I'm not sure if I'm understanding properly, though.
Answer by Noob_Vulcan · May 21, 2014 at 05:52 AM
If you want to call that method once then use bool i.e.
bool isTemp=false;
if(!isTemp){
//call you fucntion
isTemp=true;
}
i think this wat u want. If want to call it in every 1 sec then you can use WaitForSeconds
http://docs.unity3d.com/Documentation/ScriptReference/WaitForSeconds.html