Search Unity

Adding and removing gameobjects from Prefab hierarchy

Discussion in 'Prefabs' started by taylank, Jun 30, 2019.

  1. taylank

    taylank

    Joined:
    Nov 3, 2012
    Posts:
    182
    I'm hitting wall with the new prefab workflow. I have a node graph tool (NodeGraph component on a gameobject) where when the user adds a new node to the graph, it is created as a new child gameobject with a behavior on it. And when the user removes the node, the associated gameobject should be removed from the hierarchy. And to save the resulting graph, I want to store it as a prefab and have it be editable. Except I'm running into issues:

    - Once saved as a prefab, ideally the user could continue to modify the graph (and thus add new nodes perhaps) via the prefab root. Turns out, no, you can only add new gameObjects to a prefab in a scene.
    - Fine, I can live with only working in the scene and then saving the changes to the prefab via ApplyPrefabInstance. This works fine for adding nodes but turns out the user would not be able to remove nodes in this way because destroying gameobjects inside prefab instances is not allowed.

    So I'm stuck in a catch 22 situation. Is there a painless way to edit a prefab (both adding and removing child objects) via code?
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,433
    In general, if you want to maintain the nested or variant prefab relationships, you cannot remove or reorder the original prefab. You can copy or disable those parts though. I have a car script which takes a dumb (body+4wheels) model and creates a variant which is (empty+4wheels+body) that will animate better. The variant version disables the renderer in the root and recreates the same renderer in a child object.
     
  3. taylank

    taylank

    Joined:
    Nov 3, 2012
    Posts:
    182
    In my case I'm not dealing with a nested prefab though. It's a single prefab with a bunch of gameobjects underneath it (which are not themselves prefabs). I just want to create a design tool where one can change and store data in the hierarchy of the prefab.

    And in case someone suggests using ScriptableObjects instead, yeah, I have a version based on SOs already. Using gameObjects has some additional benefits in my case, for instantiation and dependency injection purposes.