Search Unity

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

Discussion in 'UGUI & TextMesh Pro' started by st33d, Aug 27, 2014.

  1. st33d

    st33d

    Joined:
    Jan 22, 2014
    Posts:
    28
    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:

    Code (csharp):
    1.  
    2. var obj = new GameObject();
    3. var renderer = obj.AddComponent<SpriteRenderer>();
    4. renderer.sprite = myAssetsFolderReference;
    5.  
    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.)
     
  2. PhilAllcock

    PhilAllcock

    Joined:
    Sep 3, 2013
    Posts:
    27
    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:
    Code (CSharp):
    1. obj.AddComponent<Image>();
    2. obj.sprite = myAssetsFolderReference;
    As well as access all the other new ui types such as button and toggle
     
    runevision likes this.
  3. st33d

    st33d

    Joined:
    Jan 22, 2014
    Posts:
    28
    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.