Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Set Canvas through code

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

  1. asotelo94


    Jan 26, 2013
    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


    Nov 20, 2010
    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.