【问题标题】:Stopping the update function in Unity在 Unity 中停止更新功能
【发布时间】:2017-09-22 22:27:36
【问题描述】:

我有一些代码在执行时会向前推动一个字符。问题是角色永远不会停止移动并永远持续下去。有没有办法让角色在 2 秒后停止移动?这是我正在使用的代码:

 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;
         }
     }

 }

我不确定是否有办法停止 update() 函数以停止角色移动。

【问题讨论】:

  • 不要在更新函数中调用storedOther.GetComponent&lt;Rigidbody&gt;()。在Start() 期间调用一次并保存刚体,当你得到一个新的对撞机时对OnTriggerStay 执行相同的操作。

标签: unity3d


【解决方案1】:

Update 函数是 Unity 脚本生命周期的一部分。如果要停止执行更新功能,则需要停用脚本。为此,您可以简单地使用:

enabled = false;

这将停用脚本生命周期的执行,从而阻止调用更新函数。

现在,您似乎正在对角色施加力以使其移动。然后你可能想要做的是,两秒钟后,移除你角色上的任何力量。为此,您可以使用协程,该函数不仅会在一个帧上执行,而且如果需要,还会在多个帧上执行。为此,您创建一个返回 IEnumerator 参数的函数,然后使用 StartCoroutine 方法调用协程:

 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;
}

这些可能是实现您想要做的不同方式。您可以选择与您当前的游戏玩法相关的内容并以这种方式修改您的脚本。

【讨论】:

  • 我添加了您编写的代码,虽然它确实阻止了角色移动,但它不断重复该过程。所以角色每 2 秒后退一点。我是否需要更改更新函数中的某些内容,使其永久停止移动角色而不是每隔几秒移动一次?
  • 问题可能是你的 isHit 变量总是等于 true。我修改了我的示例,以便在施加力后将其设置回 false。
  • 我在 Update() 中有一个 debug.log。当脚本启用时 = false;脚本显示已禁用,但更新)继续运行。
猜你喜欢
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多