Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Set Canvas through code

Discussion in 'UGUI & TextMesh Pro' started by asotelo94, Aug 21, 2014.

  1. asotelo94

    asotelo94

    Joined:
    Jan 26, 2013
    Posts:
    14
    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
     
  2. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    If liveImg is a reference to an Image component, then

    Code (csharp):
    1. Image live = Instantiate(liveImg) as Image;
    2. live.transform.parent = transform;
    If livImg is a reference to a game object or prefab, then

    Code (csharp):
    1. GameObject live = Instantiate(liveImg) as GameObject;
    2. 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.
     
    Tim-C likes this.