Search Unity

Can’t add Image to prefab variant

Discussion in '2D' started by theGreatSlutze, Jun 12, 2020.

  1. theGreatSlutze

    theGreatSlutze

    Joined:
    Jan 7, 2013
    Posts:
    25
    Hi all,

    I have a transform hierarchy I’d like to be able to use both in-game and in the UI. I need a SpriteRenderer for the former, and I believe an Image component for the latter. I wanted to use a prefab variant to do the UI version, and attach images instead of SpriteRenderers, but when I do that I see an error that the component can’t be added because it requires a different transform than the one in the base prefab.

    Is there a way to do what I’m trying to do? I expect the structure of this object to change and don’t want to have to duplicate the hierarchy when it does.
     
  2. sol-erides

    sol-erides

    Joined:
    Dec 8, 2018
    Posts:
    17
    Unity UI elements have to be children of a game object with the Canvas component. In addition, UI elements don't have a regular transform component, they have a Rect Transform. The two different types of transform can't be used on the same game object at the same time.

    Ideally you'd have separate prefabs for your UI and world objects, which is logical because they usually perform very different things. If you want to use an Image in world space though, you can set the Render Mode setting on its parent Canvas to 'World Space'. This lets the UI image exist in the same space as 'regular' game objects (with standard xyz coordinates) and behave like a regular sprite game object. So theoretically you could have both prefab variants use Canvases and Rect Transforms, with one set to use screen space and one set to use world space.