Search Unity

Question UI GameObjects Spawn without RectTransform

Discussion in 'Editor & General Support' started by Duck783, Oct 3, 2023.

  1. Duck783

    Duck783

    Joined:
    Apr 6, 2023
    Posts:
    6
    I am trying to spawn a prefab of a UI element which is an empty game object that contains an image and a text object. When I spawn it, it doesn't come in as a UI game object with a rect transform, etc. It comes in with a standard transform in world space.

    upload_2023-10-3_10-58-7.png

    Should have...
    upload_2023-10-3_11-12-35.png

    Spawns with...
    upload_2023-10-3_11-13-23.png
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,666
    You can supply optional Component types to add your GameObject via the constructor. See docs.

    You probably do NOT want to go this way however. Fiddling with RectTransforms is unbelievably tricky and hard and I won't ever try it again.

    Instead, if you need a dynamic number of "UI things," make prototypes in the scene, turn them all off at start, and Instantiate<T>() them as you go, making sure to always instantiate with parent.

    This approach is super-easy and lets you leverage the full power of the UI editing in the scene.

    See attached example package.
     

    Attached Files:

  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,812
    Are you spawning this as a child of a canvas? All rect transform stuff starts at some point with a canvas.
     
  4. Duck783

    Duck783

    Joined:
    Apr 6, 2023
    Posts:
    6
    Yes.