Change the Parent of a GameObject in script?

Is there any way to re-parent a GameObject thru script? (i.e. something like ThisObject.parent = SomeOtherObject? (not talking about AddComponent)

2 Likes

Yes; you do it through the Transform component, not the GameObject itself.

gameObject.transform.parent = otherGameObject.transform;
1 Like

I tried that but got an error message: ‘Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption’.

Well, you can’t do it to a prefab, only to objects that have been instantiated in the scene.

1 Like

ah thats it! i was caching the original instead of the scene instance. thanks all round for the quick help!