Code still trying to access Object that has been destroyed.

Error 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.
Body.LateUpdate () (at Assets/Scripts/Body.cs:32)

Body.cs:

using UnityEngine;
using System.Collections.Generic;

[RequireComponent(typeof(Rigidbody))]
public class Body : MonoBehaviour {
	
	private const float GRAVITY_CONST = 10000;

	public static List<Body> Bodies;

	
	public Rigidbody rb { get; protected set; }

	// Use this for initialization
	void Start () {
		if (Bodies == null)
			Bodies = new List<Body>();
			
		Bodies.Add (this);
		
		rb = GetComponent<Rigidbody>();
	}
	
	// Update is called once per frame
	void LateUpdate () {
		if (rb != null) {
		foreach (Body _body in Bodies) {
			if (_body == this)
				continue;
			
			float m1 = rb.mass;
			float m2 = _body.rb.mass;  **Error sends me here .... at Assets/Scripts/Body.cs:32**
			
			float r = Vector3.Distance (transform.position, _body.transform.position);
			
			float F_amp = (m1 * m2) / Mathf.Pow (r, 2);
			F_amp *= GRAVITY_CONST;
			
			Vector3 dir = Vector3.Normalize (_body.transform.position - transform.position);
			
			Vector3 F = (dir * F_amp) * Time.fixedDeltaTime;
			//Debug.Log ("Force: " + F);
			rb.AddForce (F);
		}
	}
}

Please don’t do complex physics in Update or LateUpdate. Your code will work much more reliably if any forces are applied in FixedUpdate.


Your problem however is caused by elements in Bodies being already deleted.

Simply change your check like this

if (!_body || _body == this)

UnityObjects will evaluate to false if they are currently waiting to be deleted.


Maybe add a linq Filter call to clean your array of deleted objects every few often.