【问题标题】:Unity trying to access destroyed objectUnity 试图访问被破坏的对象
【发布时间】:2020-08-19 11:37:31
【问题描述】:

我实例化了一个预制对象(子弹),如果它在 yield 返回秒数时被破坏,Unity 在我将刚体速度设置为零的行处抛出错误。无论我把它们放在哪里,它都不关心对象空检查。该脚本附加到实例化的游戏对象。

public IEnumerator GetOutState (GameObject target) {

        state = State.GetOut;
        if (state == State.GetOut && gameObject != null)  {
            rbMissile.velocity = -transform.up * speed;

            yield return new WaitForSecondsRealtime(1);

            rbMissile.velocity = Vector2.zero;


            StartCoroutine(FlyState(target));

        }

    }

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    这个脚本附加到什么游戏对象上?您正在使用

    检查附加到脚本的游戏对象是否为空
    if (state == State.GetOut && gameObject != null)  {
    

    你的意思是放

    if (state == State.GetOut && rbMissile != null)  {
    

    此外,如果这不能解决问题,您的问题很可能是:

    StartCoroutine(FlyState(target));
    

    FlyState 方法中的某些内容正在引用空游戏对象

    如果

    if (state == State.GetOut && rbMissile != null)  { 
    

    没有修复它,您的导弹在调用此方法和延迟一秒之间被破坏:

    yield return new WaitForSecondsRealtime(1);
    

    两个可能的修复方法:将 IEnumerator 更改为 void 方法并删除

     yield return new WaitForSecondsRealtime(1);
    

    或者在第二次通过后添加另一个检查

    if (rbMissle != null) {
    rbMissile.velocity = Vector2.zero;
    }
    

    【讨论】:

    • 它没有帮助。如果我关闭下一个状态转换,它仍然会在velocity.zero 行出现错误!
    • 我编辑了我的答案以供您尝试让我知道它们是如何工作的
    • 谢谢!加入 rb.Missile.velocity = vector2.zero 和 StartCoroutine(FlyState(target));到单独的空检查解决了问题!
    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多