- Home /
Destroyed child still is referenced.
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);
}
}
Answer by CodesCove · Mar 19, 2021 at 11:34 PM
I didn't analyze the code too much but just to note that when you Destroy object you just mark it to be destroyed and it will show as destroyed in the next frame, not the current one. Use DestroyImmediate() to do right away. Read here some considerations when using it https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html
Also note: You should do the Destroy object after you run any code that might still reference it in the same frame, that way you don't end up in the situation like this.
Thanks this solved it, I never knew about DestroyImmediate! Never had to use it before.
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Create multiple instances of an object 2 Answers
Is it possible to use OnMouseDown(collision other) ??? 1 Answer
Update Parent/ Children From Script? 2 Answers