How do I create an Image component on a Canvas using C#?

Sorry if this has been answered elsewhere, but the SEO on the new Canvas and Image objects isn’t great for finding answers.)

I want to dynamically create an Image on a Canvas with code. I can do similar for example with a Sprite:

var obj = new GameObject();
var renderer = obj.AddComponent<SpriteRenderer>();
renderer.sprite = myAssetsFolderReference;

But I can’t figure out what to do with Image objects because they’re not a class in MonoDevelop and they follow a separate inheritance tree to GameObject. And also the reference seems to be incomplete.

(I understand of course if we’re not expected to tinker with Images via code yet, just trying to see if I can construct an editor without dragging and dropping for a solid week.)

Have you tried adding “using UnityEngine.UI;” at the top? All the ui classes are under the ui namespace. From there you should be able to do:

obj.AddComponent<Image>();
obj.sprite = myAssetsFolderReference;

As well as access all the other new ui types such as button and toggle

1 Like

Ah - it seems to magically transmute the GameObject when I add the Image component. Also I have to add it’s transform to the Canvas object to be able to see it.

Thanks very much.