- Home /
Hot to stop a code being running over again in an update method when it is in an if statement ??
I am new to program and unity. So can we stop a code from running over and over inside an update method. Basically I have 2 " if " arguments and I want to stop the code, which is inside the if statements, from running over and over again after it gets true until the next time its gets change. Here is my code, Please someone help !
public Transform theCrossPoint;
public float lookingSpeed = 30f;
private Transform player;
private void Start()
{
player = GameManager.instance.Player.transform;
}
private void FixedUpdate()
{
bool localPlayerFocus = GameManager.instance.PlayerFocus;
if (theCrossPoint != null && localPlayerFocus) //when player in fire mood
{
Vector3 focusDir = theCrossPoint.position - transform.position; //dir that wanna see
Quaternion lookdir = Quaternion.LookRotation(focusDir); //save the dir to see
Quaternion finalDir = Quaternion.Euler(transform.rotation.eulerAngles.x, lookdir.y, transform.rotation.eulerAngles.z);
transform.rotation = Quaternion.Lerp(transform.rotation, lookdir, lookingSpeed * Time.fixedDeltaTime); //make the rotation
}
else if(!localPlayerFocus)
{
Quaternion playerRotation = player.rotation;
Quaternion headStill = Quaternion.Euler(playerRotation.eulerAngles.x, playerRotation.eulerAngles.y, playerRotation.eulerAngles.z);
transform.rotation = Quaternion.Lerp(transform.rotation, headStill, lookingSpeed * Time.fixedDeltaTime);
Debug.Log("This is running over and over again. This part needs to stop when it is true once");
}
}
Answer by ownerfate · Aug 19, 2021 at 05:07 AM
to stop something from running forever in an update function, you'll need to have a true/false if statement. ( or something that of the sort )
Once you have the If statement added, From there you'll need to then place your code within the boolean if statement.
It may look like so:
public bool a =false;
void Update (){
if(a==false){
//your code in here
a=true;
}
}
All you would need to do is have something trigger a to be false or true (Depending on how you write it)
Hope that was somewhat helpful.