Home > Software design >  MissingReferenceException after destroying an object using a coroutine in Unity
MissingReferenceException after destroying an object using a coroutine in Unity

Time:02-15

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.layer == layer)
    {
        StopAllCoroutines();
        Destroy(gameObject, 1f);
    }
}

//Coroutine is called from another script
public IEnumerator MoveRb(Vector3 destination)
{
    yield return new WaitUntil(() => rb.velocity == Vector3.zero);

    destination.y = rb.position.y;
    rb.velocity = transform.right;

    //this is where i get an error 
    yield return new WaitUntil(() => Vector3.Distance(rb.position, destination) < 0.1f); 

    rb.velocity = Vector3.zero;
}

Basically, getting "MissingReferenceException" when trying to destroy an object while running coroutine. Delay of 1 second, nor replacing "WaitUntil" with while loop and "yield return null" doesn't fix this issue. The only place where object gets destroyed is inside of "OnCollisionEnter" inside of the same gameObject script. What am I missing here?

Full exception message:

MissingReferenceException: The object of type 'Rigidbody' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

CodePudding user response:

How are you starting your coroutine? Perhaps after you've stopped all the coroutines, you're create a new one.

CodePudding user response:

The code should work in theory. I think the problem is you are trying to access the coroutine again during this 1 second destroy delay. This results in the coroutine running while the gameobject is destroyed.

If you want this 1s delay then either make sure that the coroutine can't get called again after you have collided with something or the easier way is to make the coroutine error proof. Means you check if the rigidbody is null before you use it.

  • Related