- Home /
How to stop code in the update function?
I have some code that when it executes, it pushes a character forward. The issue is that the character never stops moving and continues forever. Is there a way to stop the character from moving after 2 seconds? Here is the code I'm using:
public class meleeAttack : MonoBehaviour
{
public int speed = 500;
Collider storedOther;
bool isHit = false;
void Start()
{
}
void Update()
{
if (isHit == true )
{
storedOther.GetComponent<Rigidbody>().AddForce(transform.forward * speed);
}
}
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player" && Input.GetKeyUp(KeyCode.F))
{
storedOther = other;
isHit = true;
}
}
}
I'm not sure if there's a way to stop the update() function so it stops the character movement.
Answer by aditya007 · Nov 09, 2016 at 08:56 AM
The problem with your code is: you're not setting the bool variable "isHit" to false anywhere, because of this the if condition inside the update function will keep executing and adding force to your player and your player will always be running.
Just add line isHit = false;
inside the if statement.
Your answer

Follow this Question
Related Questions
Rigidbody Addforce cancels out Rigidbody velocity..maybe? 0 Answers
String format not working 1 Answer
Is my timer must be on Fixed Update or on Update 1 Answer
How do I implement a timer into this script that will record the total time the player has played. 2 Answers
component activate on timer 2 Answers