Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

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.