Odd behaviour of SetParent or parent =

Hi there

I just noticed something weird

I tried setting the parent of object A to be object B

That didn’t work, object’s A parent never changed, I was like : wtf?

Then I took one more look at my code and the line after setting the parent of A to be B, I was setting the parent of B to be null

I didn’t think that would cause any sort of issue since why couldn’t A’s parent be B while B has no parent?

But hey, this is Unity we’re talking about, you cannot set A’s parent to be B if the line right after you set B’s parent to be null, right? Logical! Seriously, why? How’s that a problem for B to be A’s parent??

Unity devs??

So, solution is to FIRST set B’s parent to be null, THEN set A’s parent to be B, but WHY?

I was too. I think you have a bug. Unity works as expected. Try it yourself.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// @kurtdekker - parenting - put this on a blank GameObject

public class Parenting : MonoBehaviour
{
    IEnumerator Start()
    {
        var A = new GameObject( "A");

        var B = new GameObject( "B");

// let's do it with .SetParent()
        B.transform.SetParent( this.transform);

        yield return new WaitForSeconds( 1.0f);

        A.transform.SetParent( B.transform);
        B.transform.SetParent(null);

        yield return new WaitForSeconds( 1.0f);

// now we'll do it with parent = 
        B.transform.parent = this.transform;
        A.transform.parent = null;

        yield return new WaitForSeconds( 1.0f);

        A.transform.parent = B.transform;
        B.transform.parent = null;
    }
}

Meaning it’s my code somewhere that is faulty or meaning there is a Unity bug but you cannot reproduce it?

I double checked my code see if there was anywhere else in any other script anything that would influence on that but I found not a single reference to my object A’s parent being set anywhere else than there

Very odd that just switching the line’s order makes it work, right?

Were you able to reproduce the problem with my code? Did I understand your claimed sequence correctly?

I haven’t tried it yet, I was sleeping :slight_smile:

Yes I think your code does what I explained

Not working code:

cameraHolder_transform.parent = helmet_instance.transform;
helmet_instance.transform.parent = null;

Working code:

helmet_instance.transform.parent = null;
cameraHolder_transform.parent = helmet_instance.transform;

In the first code snippet, the parent of cameraHolder doesn’t get set
In the second snippet, the parent is set properly
I tried both SetParent and parent =
Same results