0
\$\begingroup\$

Let me explain my problem with my concrete example. I have a button prefab. A button prefab has a lot of configurations: background color, background shape, background image, text, text color, button type, text size, background size, etc.

I have a few places where I use the button prefab. In some places I can just manually put the prefab into the scene in-editor and preconfigure a button. But there are other places where I need to instantiate a batch of buttons with almost the same configuration.

Sure, I could setup each of these buttons in code during the instantiation. But that seems cumbersome. So, what I did is I added a button prefab to scene. Then configured it as I wish. Then hid it in the scene. Then created a script with a reference to a GameObject and now instead of a prefab from a file explorer I put the hidden configured button in that reference. So, now during an instantiation I only need to change the enablement of the instantiated button instead of configuring it from code.

I am really eager to know if there is a better way to do what I am doing.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Why not create a second button prefab for that script, perhaps as a prefab variant of the basic button? \$\endgroup\$
    – Philipp
    May 22, 2021 at 9:43
  • \$\begingroup\$ @Philipp, because if my general button prefab will change in future I would like the changes to propagate to all buttons. I do not know if it will be possible to do in case I will use a separate prefab for this specific group of buttons. \$\endgroup\$
    – qqqqqqq
    May 23, 2021 at 7:37
  • \$\begingroup\$ You can do that with Prefab variants.. \$\endgroup\$
    – Philipp
    May 23, 2021 at 10:03

1 Answer 1

1
\$\begingroup\$

You can do that with prefab variants. A prefab variant is a prefab which inherits most of its properties from another prefab.

  1. Create your basic button
  2. Turn it into a prefab by dragging it from the scene window into the project window
  3. Drag that basic button prefab from the project into the scene to make an instance of it
  4. Modify the instance into a specialized kind of button
  5. Drag the instance from the scene into the project window.
  6. Unity will ask you if you want it to be a new, independent prefab or a prefab variant. Choose Prefab Variant.

Now any changes to the basic button will be inherited by the specialized button, and then to any buttons created from it, unless that particular property was overridden somewhere along the chain.

You can have prefab variant inheritance chains of any length.

I am using this technique a lot when I design UIs in Unity, because it makes it much easier to theme my UI after I build it. For example, experimenting with different fonts is far easier when every single Text object you have in your UI inherits from the same text prefab.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .