Quick explaination, this script is one that assigns a cursor object to the mouse. On selection of a new cursor object this script is called, where the old cursorobject is deleted and a new one added: it would seem that the problem actually lies with the previous “mousecursor” object, which is getting destroyed, is still being referenced? (see comments in code for explaination on the issue):
public void SetObjToPlace(GameObject obj)
{
objToPlace = obj;
cursorChildren = GetComponentsInChildren<Transform>();
// Clear collisionScripts
collisionScripts.Clear();
// Delete old object cursor
if (cursorChildren != null)
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
// ^ THIS OBJECT STILL GETS REFERENCED IN AddRigidBodyAndTriggerToAllChildren
}
cursorChildren = GetComponentsInChildren<Transform>();
}
// Create new object cursor
GameObject newCursor = Instantiate(obj);
newCursor.transform.parent = transform;
AddRigidBodyAndTriggerToAllChildren(transform);
// ^ This ^ function throws the error "Can't add component 'Rigidbody' to NameOfPreviouslyDestroyedObject because such a component is already added to the game object (well no shit, but it shouldn't check that destroyed child)
transform.rotation = Quaternion.identity;
newCursor.transform.position = transform.position;
SetChildShader();
}
private void AddRigidBodyAndTriggerToAllChildren(Transform parent)
{
foreach (Transform child in parent)
{
BoxCollider[] childColliders = child.gameObject.GetComponents<BoxCollider>();
if (childColliders.Length > 0)
{
Rigidbody childRB = child.gameObject.AddComponent<Rigidbody>();
// ^ This is the line throwing the error ^
childRB.useGravity = false;
// ^ Causing a nullref for childRB here
childRB.isKinematic = true;
PlacementCollision collisionScript = child.gameObject.AddComponent<PlacementCollision>();
collisionScripts.Add(collisionScript);
foreach (BoxCollider collider in childColliders)
{
collider.isTrigger = true;
}
}
AddRigidBodyAndTriggerToAllChildren(child);
}
}