The object of type "RigidBody" has been destroyed but you are still trying to acces it.

I’m following a tutorial and I’ve come across an error after the player destroys an enemy ship.


I added a new GameObject variable called enemy and I would only do what was in FixedUpdate if enemy wasn’t null to try and fix this. It worked but only if there was one enemy on screen. If there were multiple, and I killed one I still got the error in the console. Here is the code for that

public Boundary boundary;

    public float dodge;
    public float smoothing;
    public float tilt;

    public Vector2 startWait;
    public Vector2 maneuverTime;
    public Vector2 maneuverWait;

    public GameObject enemy;

    private float currentSpeed;
    private float targetManeuver;
    private static Rigidbody rb;

    void Start ()
    {
        StartCoroutine (Evade ());
        rb = GetComponent <Rigidbody> ();
        currentSpeed = rb.velocity.z;
    }

    IEnumerator Evade ()
    {
        yield return new WaitForSeconds (Random.Range (startWait.x, startWait.y));

        while (true)
        {
            targetManeuver = Random.Range (1, dodge) * -Mathf.Sign (transform.position.x);
            yield return new WaitForSeconds (Random.Range (maneuverTime.x, maneuverTime.y));
            targetManeuver = 0;
            yield return new WaitForSeconds (Random.Range (maneuverWait.x, maneuverWait.y));
        }
    }

    void FixedUpdate ()
    {
        if (enemy != null)
        {
            //I'm getting the error here
            float newManeuver = Mathf.MoveTowards (rb.velocity.x, targetManeuver, Time.deltaTime * smoothing);
            rb.velocity = new Vector3 (newManeuver, 0.0f, currentSpeed);
            rb.position = new Vector3 (
                Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
                0.0f,
                Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
            );
       
        rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);
        }
    }

I don’t know what to do to fix this so any help is appreciated.

What line in the code you posted is the line being complained about in the console? (EvasiveManeuver.cs line 47)

Why is “rb” being declared as static?

Most likely, you have this script attached to 2 or more GameObjects, and since “rb” is static the second GameObject overwrites the reference to the first Rigidbody, the third overwrites the reference to the second, and so on, so if you may have 10 enemy ship but a reference to only one rigid body, and that’s the only one you’re updating, so if you destroy the GameObject it belongs to, it is still being referenced by all other active GameObjects and that’s why you get that error. Remove “static” form the “rb” declaration and you’ll get rid of this message.

That worked. Thank you.