Search Unity

  1. How can our website serve you better? Give us your feedback. Take our survey and let us know.
    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,392
    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,392
    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.
     
unityunity