Why does destroying a gameObject influence its former children?
For context, in a 2D-Game, I have a type of skeleton-enemy consisting of multiple bones. When the enemy is killed, I want the bones to scatter around and drop on the floor. My method on the enemy called looks like this:
public override void OnDie() {
foreach (SkeletonBone bone in bones) {
bone.Init ();
}
StartCoroutine(DestroyMe());
}
IEnumerator DestroyMe() {
yield return new WaitForEndOfFrame ();
Destroy(gameObject);
}
And the Init-Method of the SkeletonBone-Class is
public void Init() {
transform.parent = null;
Rigidbody2D rb = gameObject.AddComponent<Rigidbody2D> ();
gameObject.layer = LayerMask.NameToLayer ("Bones");
rb.AddForce (new Vector2 (
Random.Range (-1, 1),
Random.Range (-1, 1)), ForceMode2D.Impulse);
rb.AddTorque (Random.Range (-3, 3));
boneCollider.enabled = true;
}
(where boneCollider is a collider on each bone, which is previously disabled because initially, the enemy only has one large collider for hit-detection.)
Each of the bones has a SpriteRenderer and the problem I have is the following: In the frame, the Skeleton-gameObject gets destroyed, all these SpriteRenderers are disabled. They are not destroyed, of course, since their transform's parent has been set to null, so only the "main" enemy gameObject is destroyed. That works fine. But why does destroying the gameObject have any effect to other gameObjects which do not have anything to do (anymore) with the destroyed one? I checked what happens if I do not destroy the enemy-object (i.e. removing the Line
StartCoroutine(DestroyMe)) - the bones stay visible. But I don't want any "dead" objects hanging around in the hierarchy, so what can I do / what am I missing?
For completeness: No errors are shown at runtime when I kill an enemy and the methods above gets called.
Answer by jwulf · Jan 03, 2017 at 06:30 PM
For now, I found at least a solution (adding it here in case someone has the same problem): Enabling the bones' SpriteRenderers in the LateUpdate()-Cycle after the Init() will cause the sprites to remain visible.
However, that is not quite an explanation for the behavior described above...