SetParent doesnt work

This is a little part of code I wrote and even though i set the parent 1 line before it Logs the base parent of part, it doesnt log Target.name but the name of the parent that was set before this, it logs all the correct data except the parent.

I disabled every single script in the scene to test if there might be some interference with other scripts and it does not work.

Any solutions?

part.transform.SetParent(target.transform, true);
Debug.Log(part.name + " " + part.transform.parent.name + " " + target.name);

Have you made sure that target.transform!=part.transform.parent?

–

2 Answers

2

Destroy() is not instant, this is true, but SetParent() is. 100%.

Destroy() is responsible for asset/data being unloaded, resources being freed so it makes sense to not block the main thread as there are no dependencies here. SetParent is a different case as game logic depends on this being instant. There is no SetParentAsync just yet.

In my long experience I have never had to deal with weird operations with the SetParent() method, but I suppose it works just like the Destroy() method, it is not istant, in fact it is requiered a bit of time in order to let Unity complete the operation.

To test if I am correct, try this:

void Start() //I suppose you are using the Start/Awake method
{
   part.transform.SetParent(target.transform, true);
   Invoke(nameof(Debug), Time.deltaTime); //We call the debug method NOT INSTANTLY, but after a frame has been rendered (deltaTime)
}
void Debug()
{
   Debug.Log(part.name + " " + part.transform.parent.name + " " + target.name);
}