Set Canvas through code

As simple as is sounds. I’m trying to instantiate an Image, but can’t parent it to the canvas since there is no transform (only RectTransform).

RectTransform live = Instantiate(liveImg) as RectTransform;
live.parent = transform;

… and yeah, this script is attached to the canvas

If liveImg is a reference to an Image component, then

Image live = Instantiate(liveImg) as Image;
live.transform.parent = transform;

If livImg is a reference to a game object or prefab, then

GameObject live = Instantiate(liveImg) as GameObject;
live.transform.parent = transform;

RectTransform class is inhereted from Transform, therefore whenever you need a reference to Transform you may use a reference to RectTransform instead.

1 Like