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.
Should have…
Spawns with…
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() 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.
9557998–1351300–DynamicUIDemo.unitypackage (94 KB)
Are you spawning this as a child of a canvas? All rect transform stuff starts at some point with a canvas.