Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping the update function in Unity

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.

like image 864
sam1319 Avatar asked Sep 03 '26 08:09

sam1319


1 Answers

The Update function is part of the life cycle of a Unity script. If you want to stop the Update function to be executed, you need to deactivate the script. For this, you can simply use:

enabled = false;

This will deactivate the execution of the life cycle of your script, and so prevent the Update function to be called.

Now, it looks like you are applying a force to your character to make it move. What you might want to do then is, after two seconds, remove any force present on your character. For that, you can use a coroutine, which is a function that will not just be executed on one frame, but on several frames if needed. For that, you create a function which returns an IEnumerator parameter, and you call the coroutine with the StartCoroutine method:

 bool forcedApplied = false;

void Update()
{
    if (isHit == true && forceApplied == false)
    {
        storedOther.GetComponent<Rigidbody>().AddForce(transform.forward * speed);

        forceApplied = true;

        StartCoroutine(StopCharacter);

        isHit = false;
    }

}

IEnumerator StopCharacter()
{
    yield return new WaitForSeconds(2);

    storedOther.GetComponent<Rigidbody>().velocity = Vector3.zero;

    forceApplied = false;
}

Those might be different ways to achieve what you want to do. It's up to you to choose what seems relevant to your current gameplay and to modify your script this way.

like image 157
Izukani Avatar answered Sep 05 '26 10:09

Izukani