Search Unity

Design pattern: similar prefabs

Discussion in 'Prefabs' started by Eyal-Mygameslab, Jan 18, 2019.

  1. Eyal-Mygameslab

    Eyal-Mygameslab

    Joined:
    Dec 12, 2018
    Posts:
    1
    I was wondering about the optimal design pattern for cases where I want a number of similar-yet-different objects (let's say enemies or even tiles).

    Let's say I need like a dozen or two, or even 50 variants of the same object, which differ in some data (e.g. hp) and look (e.g. sprite) but have the same animations, collision, etc.

    In such a case,
    Should i be creating a separate variant per prefab and modify the data and image for each?
    or should i have one generic prefab, and apply the relevant data and image by code upon creation, based on the specific (let's say randomized) type?
    Or maybe some other method?

    Thanks!
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,913
    Either way works, but using less prefabs will lead to less potential bugs.

    Prefabs are easier to use because you can see exactly how it will look, instead of adjusting the raw data blind, but for something simple like HP and sprite switching, it might be easier to use one generic prefab that reads from a ScriptableObject and builds itself at runtime via factory pattern.

    Also, the prefab system won't allow reordering of its children, so anything parented will be added to the bottom. Probably not an issue.

    I use multiple variants when I need position/collision mesh adjustment that I don't want to do blind. For example, every ship in my game is prefab variant, and every building in my city-builder is also a variant. Adjusting raw data to create them was too fiddly.