Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Resolved How to add a child to a prefab instance via editor script?

Discussion in 'Prefabs' started by Brady, Jun 15, 2020.

  1. Brady

    Brady

    Joined:
    Sep 25, 2008
    Posts:
    2,474
    I have an editor script where I need the ability to add a child object to an instance of a prefab, similar to how you can drag a GameObject onto an instance of a prefab in the hierarchy, and it gets added as an override at the bottom of the instance's hierarchy.

    Specifically, I'm instantiating prefab instances in-editor (so they remain connected to the source prefab), and then I need to add a child to it as an override. I do NOT need to add the child to the original source prefab, just to the instance in the currently open scene. Again, this is via editor script and in edit mode, not in play mode.

    I've tried the naive approach of using SetParent(), and I receive the following error:

     
  2. Brady

    Brady

    Joined:
    Sep 25, 2008
    Posts:
    2,474
    My error -- it turns out SetParent() works in an editor script for this purpose. The error I was receiving was actually due to reflection I was doing on the Transform component, and it was trying to set the "parent" and "parentInternal" fields via reflection, yield the error. I had to add an exception based on the component type and property name so that it did not attempt to set these fields.